获取< a>的href < li>中的标签 [英] Getting the href of <a> tag which is in <li>

查看:86
本文介绍了获取< a>的href < li>中的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取给定代码中类"Subforum"下的所有标签的href?

How to get the href of the all the tag that is under the class "Subforum" in the given code?

<li class="subforum">
<a href="Link1">Link1 Text</a>
</li>
<li class="subforum">
<a href="Link2">Link2 Text</a>
</li>
<li class="subforum">
<a href="Link3">Link3 Text</a>
</li>

我已经尝试了这段代码,但是显然没有用.

I have tried this code but obviously it didn't work.

Bs = BeautifulSoup(requests.get(url).text,"lxml")
Class = Bs.findAll('li', {'class': 'subforum"'})
for Sub in Class:
    print(Link.get('href'))

推荐答案

href属于a标签,而不是li标签,请使用li.a获取a标签

The href belongs to a tag, not li tag, use li.a to get a tag

文档:使用标签名称进行导航

import bs4

html = '''<li class="subforum">
 <a href="Link1">Link1 Text</a>
 </li>
 <li class="subforum">
<a href="Link2">Link2 Text</a>
</li>
<li class="subforum">
<a href="Link3">Link3 Text</a>
</li>`<br>'''

soup = bs4.BeautifulSoup(html, 'lxml')
for li in soup.find_all(class_="subforum"):
    print(li.a.get('href'))

退出:

Link1
Link2
Link3

为什么要使用class_:

搜索具有特定CSS类的标签非常有用,但是CSS属性的名称class 在Python中是保留字.使用类作为关键字参数会出现语法错误.从Beautiful Soup 4.1.2开始,您可以使用关键字参数class_按CSS类进行搜索.

It’s very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, class, is a reserved word in Python. Using class as a keyword argument will give you a syntax error.As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_.

这篇关于获取&lt; a&gt;的href &lt; li&gt;中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆