Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何访问标签';s属性值与BeautifulSoup_Python_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 如何访问标签';s属性值与BeautifulSoup

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> "

我正在使用BeautifulSoup和web抓取请求。我知道如何提取标签之间的属性,但如果我想要的是标签下面的数字
'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