【问题标题】:Parse div element from html with style attributes使用样式属性从 html 中解析 div 元素
【发布时间】:2022-01-27 04:46:46
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup 从 html 文件中获取 div 元素内的文本 Something here I want to get

这就是部分代码在 html 中的样子:

<div xmlns="" id="idp46819314579224" style="box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #d43f3a; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;" class="" onclick="toggleSection('idp46819314579224-container');" onmouseover="this.style.cursor='pointer'">Something here I want to get<div id="idp46819314579224-toggletext" style="float: right; text-align: center; width: 8px;">
                -
            </div>
</div>

这就是我尝试做的:

vu = soup.find_all("div", {"style" : "background: #d43f3a"})

for div in vu:
    print(div.text)

我使用循环是因为有几个具有不同 id 的 div,但它们都具有相同的背景颜色。它没有错误,但我没有输出。

如何以背景色为条件获取文本?

【问题讨论】:

  • 将其更改为background-color: #d43f3a 有帮助吗?
  • 可以运行,但还是没有输出。是因为不能用style作为条件吗?

标签: python parsing beautifulsoup


【解决方案1】:

style 属性里面还有其他内容

style="box-sizing: ....; ....;"

您当前的代码询问if style == "background: #d43f3a" 不是。

你可以做的是问if "background: #d43f3a" in style——一个子字符串检查。

一种方法是传递regular expression

>>> import re
>>> vu = soup.find_all("div", style=re.compile("background: #d43f3a"))
... 
... for div in vu:
...     print(div.text.strip())
Something here I want to get

你也可以用CSS Selectors说同样的话

soup.select('div[style*="background: #d43f3a"]')

或者通过传递一个函数/lambda

>>> vu = soup.find_all("div", style=lambda style: "background: #d43f3a" in style)
... 
... for div in vu:
...     print(div.text.strip())
Something here I want to get

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 2023-03-25
    • 2014-09-23
    • 2023-03-07
    • 2020-06-13
    • 2012-08-03
    • 2018-05-01
    • 1970-01-01
    相关资源
    最近更新 更多