我想选择至少具有一个以“responsive-”开头的属性的所有元素
<div reponsive-devices="desktop"></div> #Select this
<ul responsive-os="android"></ul> # Select this
<div class="responsive-"></div> # DON'T select this
我已经尝试过这个:Can I select all elements whose attribute names (not values) start with a certain string?但这对我没有帮助。
有人知道吗?
最佳答案
这并不简单,但您可以迭代标记并检查是否有任何属性以 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>]
关于Python BeautifulSoup 选择属性开头的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505565/