【问题标题】:Python RegEx with Beautifulsoup 4 not working带有 Beautifulsoup 4 的 Python RegEx 不起作用
【发布时间】: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

【问题讨论】:

标签: python regex python-3.x beautifulsoup


【解决方案1】:

不要使用正则表达式,而是将您要查找的类放在一个列表中:

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

【讨论】:

  • 嗯,这可能在这里工作,但稍后我确信在不久的将来我将不得不处理只能使用 RegEx 轻松处理的场景。 Ex- "common text sighting_46....." , to find all tags starting with 46 in the example and followed by, lets say 5 numbers.
【解决方案2】:

要扩展@Andy 的答案,您可以列出类名和编译的正则表达式:

soup.find_all('div', {'class': ["common", "text", re.compile(r'sighting_\d{5}')]})

请注意,在这种情况下,您将获得具有指定类/模式之一的 div 元素 - 换句话说,它是 commontextsighting_ 后跟五位数字。

如果您想让它们与“and”连接,一种选择是通过将文档解析为“xml”来关闭对“class”属性的特殊处理:

soup = BeautifulSoup(html_doc, 'xml')
all_findings = soup.find_all('div', class_=re.compile(r'common text sighting_\d{5}'))
print all_findings

【讨论】:

  • 现在我知道我实际上是在寻找将 RegEx 应用于标签属性的每个值。对于完全匹配的示例,我无法弄清楚如何处理多个正则表达式案例。
  • 我今天遇到了一个问题,它匹配只有"common" 作为值的类。如何使每个匹配都满足?
  • @Shivendra 我已经用一个选项更新了答案。问题是,如果您将其解析为 HTML,您会将 class 视为多值属性..
  • 可以做到,但我使用了一个不太优雅的解决方法。在for loop 中,我分别检查每个正则表达式,并选择通过所有检查的元素。最初,我将候选人列入候选名单,以通过您之前提供的单行词soup.find_all('div', {'class': ["common", "text", re.compile(r'sighting_\d{5}')]}) 进一步检查。 ;)
猜你喜欢
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多