Python 如何访问标签';s属性值与BeautifulSoup
我正在使用BeautifulSoup和web抓取请求。我知道如何提取标签之间的属性,但如果我想要的是标签下面的数字Python 如何访问标签';s属性值与BeautifulSoup,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我正在使用BeautifulSoup和web抓取请求。我知道如何提取标签之间的属性,但如果我想要的是标签下面的数字'4.31',你知道如何获取它吗 您可以像这样读取属性title值: from bs4 import BeautifulSoup response = """ <html> <div class="starRating" title="4.31"> <svg> </svg> </div> </html> "
'4.31'
,你知道如何获取它吗
您可以像这样读取属性title
值:
from bs4 import BeautifulSoup
response = """
<html>
<div class="starRating" title="4.31">
<svg>
</svg>
</div>
</html>
"""
soup = BeautifulSoup(response, 'lxml')
print(soup.find('div', {'class': 'starRating'})['title'])
看
`
标记可以具有任意数量的属性。标签
有一个属性“id”,其值为“boldest”。通过将标记视为字典,可以访问标记的属性
您可以像这样读取属性title
值:
from bs4 import BeautifulSoup
response = """
<html>
<div class="starRating" title="4.31">
<svg>
</svg>
</div>
</html>
"""
soup = BeautifulSoup(response, 'lxml')
print(soup.find('div', {'class': 'starRating'})['title'])
看
`
标记可以具有任意数量的属性。标签
有一个属性“id”,其值为“boldest”。通过将标记视为字典,可以访问标记的属性
您可以使用lambda查询具有匹配的title
属性的元素,然后使用[“title”]
键提取所需的数据:
>>> soup.find(lambda x: x.name == "div" and "title" in x.attrs)["title"]
'4.31'
或者使用CSS选择器:
>>> soup.select_one("div[title]")
<div class="starRating" title="4.31"></div>
>>汤。选择一个(“div[title]”)
更简单的是,将目标属性用作kwarg:
>>> soup.find("div", title=True)
<div class="starRating" title="4.31"></div>
>soup.find(“div”,title=True)
尝试将title
属性从没有该属性的元素中拉出将引发KeyError
,因此值得提前筛选。如果您想要多个结果的列表,请使用find_all
或select
。您可以使用lambda查询具有匹配title
属性的元素,然后使用[“title”]
键提取所需的数据:
>>> soup.find(lambda x: x.name == "div" and "title" in x.attrs)["title"]
'4.31'
或者使用CSS选择器:
>>> soup.select_one("div[title]")
<div class="starRating" title="4.31"></div>
>>汤。选择一个(“div[title]”)
更简单的是,将目标属性用作kwarg:
>>> soup.find("div", title=True)
<div class="starRating" title="4.31"></div>
>soup.find(“div”,title=True)
尝试将title
属性从没有该属性的元素中拉出将引发KeyError
,因此值得提前筛选。如果您想要多个结果的列表,请使用find_all
或select