[英]How to select tags by attribute value with Beautiful Soup
我有以下 HTML 片段:
>>> a
<div class="headercolumn">
<h2>
<a class="results" data-name="result-name" href="/xxy> my text</a>
</h2>
仅当属性 data-name="result-name" 时,我才尝试选择标题列
我试过了:
>>> a.select('a["data-name="result-name""]')
这给出:
ValueError: Unsupported or invalid CSS selector:
我怎样才能让它工作?
你可以简单地这样做:
soup = BeautifulSoup(html)
results = soup.findAll("a", {"data-name" : "result-name"})
html = """
<div class="headercolumn">
<h2>
<a class="results" data-name="result-name" href="/xxy> my text</a>
</h2>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for d in soup.findAll("div",{"class":"headercolumn"}):
print d.a.get("data-name")
print d.select("a.results")
result-name
[<a class="results" data-name="result-name" href="/xxy> my text</a></h2>"></a>]
选择类或 ID
soup.select('a.gamers') # select an `a` tag with the class gamers
soup.select('a#gamer') # select an `a` tag with the id gamer
选择单个属性:
soup.select('a[attr="value"]')
选择多个属性:
attr_dict = {
'attr1': 'val1',
'attr2': 'val2',
'attr3': 'val3'
}
soup.findAll('a', attr_dict)
你可以在soup.select
使用任何CSS选择器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.