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

2024-04-25 14:00:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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,使用了tag的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

Tags: in标记revaluestylehtmltag样式
2条回答

我没有找到一个方法来得到它。所以我使用re模块作为解决方法。你知道吗

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

if tag.has_attr('style') and border_re.search(tag.attrs['style']):
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

相关问题 更多 >