【发布时间】:2015-11-06 20:51:04
【问题描述】:
我想查找所有div 名称中具有特定模式的class 标记,但我的代码无法正常工作。
这是代码sn-p
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。
【问题讨论】:
-
看看this SO post。有帮助吗?如果它回答了您的问题,那么您的问题就是重复的。因此,bs4 将
common text sighting_4619012视为commontextsighting_4619012的数组。正则表达式分别应用于它们中的每一个。 -
我找到了那个帖子并尝试过。它没有用。
-
啊,我想我明白你的意思了。你提到的那篇文章没有提到
Regex is applied to each of them separately,所以我无法弄清楚。但是,如果我们想根据列表的 2 项找到匹配项(使用正则表达式)怎么办。前 -"text", "sighting_4619012"Double Ah,我想我已经用 @alecxe 的回答解决了我的疑问。 -
在这里也复制我的评论 - 我今天遇到了一个问题,它匹配只有“common”作为值的类。如何使每个匹配都满足?
标签: python regex python-3.x beautifulsoup