阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程
解答
你使用 find_all 方法来查找 HTML 中的字符串,但是却什么都找不到。这可能是因为 HTML 中的字符串包含了特殊字符或编码。
在 Python 中,字符串默认使用 Unicode 编码,如果 HTML 中的字符串使用了其他编码,可能会导致 find_all 方法无法正确地匹配。
在你的情况中,你可以尝试使用 encode 方法将字符串转换为 UTF-8 编码,然后再使用 find_all 方法:
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
string = "¥"
encoded_string = string.encode('utf-8').decode('unicode_escape')
results = soup.find_all(string=encoded_string)
在上面的代码中,我们使用 encode 方法将字符串转换为 UTF-8 编码,然后使用 decode 方法将编码后的字符串转换回 Unicode 编码。这样可以确保 find_all 方法正确地匹配 HTML 中的字符串。
如果你仍然无法找到结果,可以尝试使用 find_all 方法的其他参数,例如 text 参数,可以指定查找的文本内容:
results = soup.find_all(text=string)
这将查找 HTML 中的所有文本内容包含 string 字符串的元素。