测试标签在BeautifulSoup中是否具有样式

时间:2019-10-23 02:41:32

标签: python html beautifulsoup tags styles

我正在使用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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

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