[英]How to select a tag in beautifulsoup with an attribute not knowing the value of that attribute?
[英]Python Beautifulsoup : how to find a tag by attribute value without knowing corresponding attribute name?
假设我们有一个不知道属性名称的属性值“xyz”。 这意味着我们可以匹配
<a href="xyz">
但是也
<div class="xyz">
是否可以搜索此类标签?
一种解决方案是在find_all
函数中使用lambda
。
例子:
data = '''<a href="xyz">a</a>
<div class="somethingelse">b</div>
<div class="xyz">c</div>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
for tag in soup.find_all(lambda tag: any('xyz' in tag[a] for a in tag.attrs)):
print(tag)
印刷:
<a href="xyz">a</a>
<div class="xyz">c</div>
[tag for tag in soup.find_all(True)
if "xyz" in tag.attrs.values() or ["xyz"] in tag.attrs.values()]
说明:
soup.find_all(True)
查找所有标签(因为True
是针对每个评估为True
标签)。
tag.attrs
是tag
所有属性的字典。
href
、 class
、 id
)不感兴趣,只对它们的值tag.attrs.values()
——所以我们使用tag.attrs.values()
。class="xy"
),因此它们在attrs
字典中的值是一个列表(例如["x", "y"]
)。 所以我们测试了"xyz"
和["xyz"]
可能性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.