簡體   English   中英

使用 bs4 在類中選擇一個標簽

[英]Select a tag inside a class with bs4

我正在嘗試獲取這部分 html 的 href:

<h3 class="post-title entry-title" itemprop="name">
<a href="http://sslproxies24.blogspot.it/2016/10/01-10-16-free-ssl-proxies-1070.html">01-10-16 | Free SSL Proxies (1070)</a>
</h3>

所以我創建了這個腳本:

import urllib.request
from bs4 import BeautifulSoup

url = "http://sslproxies24.blogspot.it/"
soup = BeautifulSoup(urllib.request.urlopen(url))
for tag in soup.find_all("h3", "post-title entry-title"):
    links = tag.get("href")

但是鏈接,沒有找到任何東西。 這是因為,我用 bs4 選擇的“post-title entry-title”類沒有屬性“href”......

事實上輸出:

print (tag.attrs)

是:

{'itemprop': 'name', 'class': ['post-title', 'entry-title']}

如何選擇“a”元素並獲取 href 中的鏈接?

您可以通過獲取內部a元素來快速解決它:

for tag in soup.find_all("h3", "post-title entry-title"):
    link = tag.a.get("href")

其中tag.atag.find("a")的快捷方式。

或者,您可以將a元素直接與CSS 選擇器匹配:

for a in soup.select("h3.post-title.entry-title > a"):
    link = a.get("href")

其中 dot 是屬性選擇器, >表示直接父子關系

或者,您可以檢查itemprop屬性而不是類:

for a in soup.select("h3[itemprop=name] > a"):
    link = a.get("href")

暫無
暫無

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

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