Select 带有 bs4 的 class 内的标签

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 select编辑的 class "post-title entry-title" 没有属性 "href"...

实际上输出为:

print (tag.attrs)

是:

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

如何处理 select "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 selector:

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

其中点是class属性选择器,>表示直接父子关系

或者,您可以检查 itemprop 属性而不是 class:

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