我想找到所有在其 class
名称中具有特定模式的 div
标签,但我的代码无法按预期工作。
这是代码片段
soup = BeautifulSoup(html_doc, 'html.parser')
all_findings = soup.findAll('div',attrs={'class':re.compile(r'common text .*')})
其中 html_doc
是带有以下 html 的字符串
<div class="common text sighting_4619012">
<div class="hide-c">
<div class="icon location"></div>
<p class="reason"></p>
<p class="small">These will not appear</p>
<span class="button secondary ">wait</span>
</div>
<div class="show-c">
</div>
</div>
但是 all_findings
作为一个空列表出现,而它应该找到一项。
它在完全匹配的情况下工作
all_findings = soup.findAll('div',attrs={'class':re.compile(r'hide-c')})
我正在使用bs4
。
最佳答案
不要使用正则表达式,而是将您要查找的类放入列表中:
all_findings = soup.findAll('div',attrs={'class':['common', 'text']})
<小时/>
示例代码:
from bs4 import BeautifulSoup
html_doc = """<div class="common text sighting_4619012">
<div class="hide-c">
<div class="icon location"></div>
<p class="reason"></p>
<p class="small">These will not appear</p>
<span class="button secondary ">wait</span>
</div>
<div class="show-c">
</div>
</div>"""
soup = BeautifulSoup(html_doc, 'html.parser')
all_findings = soup.findAll('div',attrs={'class':['common', 'text']})
print all_findings
<小时/>
输出:
[<div class="common text sighting_4619012">
<div class="hide-c">
<div class="icon location"></div>
<p class="reason"></p>
<p class="small">These will not appear</p>
<span class="button secondary ">wait</span>
</div>
<div class="show-c">
</div>
</div>]
关于Python RegEx 与 Beautifulsoup 4 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995815/