<div id="a">123 456</div>
<div id="b">456</div>
<div id="c">123 456 789</div>
soup.findAll('div', text = re.compile('456'))
仅返回div b,没有其他值。
soup.findAll('div', text = re.compile('45'))
仅返回div b,没有其他值。
如何返回实际上与特定字符串部分匹配的其他DIV?
答案 0 :(得分:0)
您问题的答案几乎类似于this answer。您要做的只是稍微调整lambda
函数。这是完整的代码:
from bs4 import BeautifulSoup
html = '''
<div id="a">123 456</div>
<div id="b">456</div>
<div id="c">123 456 789</div>
'''
soup = BeautifulSoup(html,'html5lib')
divs = soup.find_all("div", text=lambda text: text and '456' in text)
输出:
>>> divs
[<div id="a">123 456</div>, <div id="b">456</div>, <div id="c">123 456 789</div>]