"Bs4内选择一个类中的标签"

2024-10-01 17:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取此部分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>

所以我创建了这个脚本:

^{pr2}$

但是links找不到任何东西。这是因为,我用bs4选择的类“post title entry title”没有属性“href”。。。在

事实上:

print (tag.attrs)

是:

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

如何选择“a”元素并在href中获取链接?在


Tags: namefreehttpssltitlehtmlitpost
1条回答
网友
1楼 · 发布于 2024-10-01 17:35:20

通过获取内部a元素,可以快速解决该问题:

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

{{cd2>是快捷键。在

或者,您可以直接将a元素与CSS selector匹配:

^{pr2}$

其中dot是一个属性选择器,>表示直接父子关系。在

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

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

相关问题 更多 >

    热门问题