簡體   English   中英

如何使用 BeautifulSoup 訪問標簽的屬性值

[英]How to access tag's attribute value with BeautifulSoup

我正在使用 BeautifulSoup 和網頁抓取請求。 我知道如何提取標簽之間的屬性,但是如果我想要的是標簽中下面的數字'4.31' ,知道如何獲取它嗎?

<div class="starRating" title="4.31">
<svg
 ...
</svg>
</div>

我試過了:

soup.find('div',{'class':'starRating'})
soup.find('title')

什么都不返回,所以數字基本上是標簽......

您可以像這樣讀取屬性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'])

輸出:

4.31

請參閱https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes `

一個標簽可以有任意數量的屬性。 標簽<b id="boldest">有一個屬性“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>

更簡單的是,使用 target 屬性作為 kwarg:

>>> soup.find("div", title=True)
<div class="starRating" title="4.31"></div>

嘗試從沒有它的元素中提取title屬性會引發KeyError ,因此值得提前過濾。 使用find_allselect如果您想要多個結果的迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM