【问题标题】:find_all with multiple expressions for tags that include both attribute values specifiedfind_all 具有多个表达式,用于包含指定的两个属性值的标记
【发布时间】:2019-05-31 12:13:37
【问题描述】:

我正在使用属性值 h5 和 ls3 从 HTML 文件中提取所有标签,但我不确定如何格式化搜索,因此它不会返回 h5 的所有实例和 ls3 的所有实例。

regex = re.compile('h5')
re2 = re.compile('ls3')

ly = []


for EachPart in soup.find_all("div", {"class": regex}):
    ly.append(EachPart)

目前仅搜索 h5(如预期的那样),但我如何格式化 find_all 搜索以搜索 re2regex?实际上,在下面我需要拉出具有 h5 和 ls3 的标签,而不是专门为 h5 的标签

示例 HTML 标签:

<div class="t m0 x42 h5 y18b ff2 fs2 fc0 sc0 ls0 ws0">total </div>

<div class="t m0 xbd h5 y18b ff2 fs2 fc0 sc0 ls0 ws0"> </div>

<div class="t m0 x79 h5 y18b ff2 fs2 fc0 sc0 ls3 ws0">£m<span class="ls0"> </span></div>

<div class="t m0 x0 h5 y628 ff2 fs2 fc0 sc0 ls3 ws0">17.<span class="ls0"> <span class="_ _4"></span>Website policy<span class="_ _0"></span> </span></div>

【问题讨论】:

  • 发布html示例代码
  • 给出需要解析的 html 的链接。你想收集哪些类名?

标签: python html regex web-scraping beautifulsoup


【解决方案1】:

使用带有 AND 语法的 css 选择器。下面指定具有这两个属性的元素。比find 和正则表达式更高效。

items = [item.text for item in soup.select('.ls3.h5')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多