【问题标题】:Test if a tag has a style in BeautifulSoup测试标签是否在 BeautifulSoup 中具有样式
【发布时间】:2020-02-19 05:18:20
【问题描述】:

我正在用beautifulsoup 解析一个html。我需要检查标签是否具有类似border.*:.*px 的样式。

我可以找到所有带有样式的标签,

soup.find_all(["tr"],style=re.compile(r'border.*:[^:]*px'))

但是我必须按顺序遍历html,所以对于一个标签,如何检查它是否具有r'border.*:[^:]*px'的样式。

我也参考了Test if an attribute is present in a tag in BeautifulSoup,使用了has_attr标签的方法,但是好像不支持正则。

value = re.compile(r'border.*:[^:]*px')
tag.has_attr("{'style':"+value+"}")

但它显示

TypeError                                 Traceback (most recent call last)
<ipython-input-202-1e077ea6ea4c> in <module>
      1 value = re.compile(r'border.*:[^:]*px')
----> 2 tag.has_attr("{'style':"+value+"}")

TypeError: must be str, not _sre.SRE_Pattern

【问题讨论】:

  • 看看这个?希望有 3 种不同的方法可以做到这一点Beautiful Soup Tag Style
  • @EGC 再次感谢您。该链接是关于如何找到具有某种风格的标签。我的问题是要检查标签是否有样式。
  • @EGC 在我的问题中,我说过我知道如何找到具有某种风格的标签。

标签: python html beautifulsoup tags styles


【解决方案1】:

我没有找到 BeautifulSoup4 的方法来获取它。所以我使用re 模块作为解决方法。

import re
border_re = re.compile(r'border.*:[^:]*px')

if tag.has_attr('style') and border_re.search(tag.attrs['style']):

【讨论】:

    【解决方案2】:
    def foo(tag):
        import re
        tag_style = tag.attrs.get('style')
        return bool(re.search(r'border.*:[^:]*px', tag_style)) if tag_style else False
    

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2011-06-28
      • 2016-05-10
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多