获取< a>的href < li>中的标签 [英] Getting the href of <a> tag which is in <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_
.
这篇关于获取< a>的href < li>中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!