在使用find_all()方法时,可以使用text参数来查找标签内的文本内容。当一个标签有多个文本节点时,text会将其合并为一个字符串进行查找。因此,如果在一个标签内存在多个文本节点,并且其中一个节点中存在目标文本,而其他节点没有该文本,则使用find_all()方法是无法查找到目标的。
解决方法是使用正则表达式来匹配包含目标文本的整个文本字符串,然后使用find_all()方法中的text参数进行查找。
示例代码:
import re from bs4 import BeautifulSoup
html = '''
hello
targetworld
target!
soup = BeautifulSoup(html, 'html.parser') targets = ['target', 'target1']
for t in targets: pattern = re.compile(t) tags = soup.find_all(text=pattern)
print(tags) # 输出匹配结果