Python BeautifulSoup选择所有属性以开头的元素

时间:2019-06-08 10:35:35

标签: python beautifulsoup

我要选择所有具有至少一个以“ response-”开头的属性的元素

GradientBoostingClassifier

我已经尝试过:Can I select all elements whose attribute names (not values) start with a certain string?,但是它无济于事。

有人有什么主意吗?

1 个答案:

答案 0 :(得分:1)

这并不简单,但是您可以遍历标记并检查是否有任何属性以responsive开头。

请参见以下代码:

from bs4 import BeautifulSoup

data = '''<div responsive-devices="desktop"></div>
<ul responsive-os="android"></ul>
<div class="responsive-"></div>'''

soup = BeautifulSoup(''.join(data))

responsive_tag_list = soup.findAll(
                lambda tag:
                any([i.startswith('responsive-') for i in tag.attrs])
                )

print(responsive_tag_list)

输出:

[<div responsive-devices="desktop"></div>, <ul responsive-os="android"></ul>]