查找标签在文本中包含部分字符串

时间:2020-10-31 12:07:41

标签: python-3.x beautifulsoup

<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?

1 个答案:

答案 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>]
相关问题