簡體   English   中英

使用 bs4 抓取數據

[英]Scraping data with bs4

我有這行 html:

<td title="Druid"><a href="/pvp/druid"><img src="/images/classes/druid.png" class="img-responsive center" alt="Druid"></a></td>

使用 python 和漂亮的湯,我想從<td title="Druid">訪問“德魯伊”以存儲為變量。

如果要訪問 td 的標題:

bs4.BeautifulSoup(data).find("td")["title"]

要獲取標簽的屬性,請將其視為字典:

soup.find('td').get('title')

或者

soup.find('td')['title']

注意: .get('title', 'some default value')允許您在缺少鍵或省略時提供默認值None ,而['title']將引發 KeyError

例子

from bs4 import BeautifulSoup
html='''<td title="Druid"><a href="/pvp/druid"><img src="/images/classes/druid.png" class="img-responsive center" alt="Druid"></a></td>'''
soup = BeautifulSoup(html)

character = soup.find('td').get('title')

print(character)

Output

Druid

暫無
暫無

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

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