Python RegEx 与 Beautifulsoup 4 不起作用

标签 python regex python-3.x beautifulsoup

我想找到所有在其 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/

相关文章:

python - 计算质数

javascript - 在javascript中,我们可以使用正则表达式将字符串与循环部分匹配,但不要拆分它

c# - 将 youtube url 转换为 iframe 嵌入代码

python - 递归基础表示

python - 如何将字符串解释为字节?

python-3.x - 在 Ubuntu 上为 python3 安装 matplotlib

python - 如何在 matplotlib 中制作空白子图?

python - 在旧版 Python 中创建带有可变参数的 Typing.Annotated 实例

python - 如何在django View 函数中获取域名?

python - 哪个是作为参数的 token 的 django url 正则表达式?