[英]Get value of attribute using CSS Selectors with BeutifulSoup
我正在使用Python
進行網絡BeutifulSoup
並使用BeutifulSoup
庫
我有這樣的HTML
標記:
<tr class="deals" data-url="www.example2.com">
<span class="hotel-name">
<a href="www.example2.com"></a>
</span>
</tr>
<tr class="deals" data-url="www.example3.com">
<span class="hotel-name">
<a href="www.example3.com"></a>
</span>
</tr>
我想在所有<tr>
獲取data-url
或href
值。 如果我能獲得href
價值,那就更好了
這是我相關代碼的一小段:
main_url = "http://localhost/test.htm"
page = requests.get(main_url).text
soup_expatistan = BeautifulSoup(page)
print (soup_expatistan.select("tr.deals").data-url)
# or print (soup_expatistan.select("tr.deals").["data-url"])
您可以使用CSS選擇器tr.deals span.hotel-name a
進入鏈接:
from bs4 import BeautifulSoup
data = """
<tr class="deals" data-url="www.example.com">
<span class="hotel-name">
<a href="wwwexample2.com"></a>
</span>
</tr>
"""
soup = BeautifulSoup(data)
print(soup.select('tr.deals span.hotel-name a')[0]['href'])
印刷品:
wwwexample2.com
如果您有多個鏈接,請對其進行迭代:
for link in soup.select('tr.deals span.hotel-name a'):
print(link['href'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.