BeautifulSoup 获取 href [重复]
- 2025-01-15 08:45:00
- admin 原创
- 100
问题描述:
我有以下内容soup
:
<a href="some_url">next</a>
<span class="class">...</span>
我想从中提取 href,"some_url"
如果我只有一个标签,我可以做到这一点,但这里有两个标签。我也可以获取文本'next'
,但这不是我想要的。
另外,有没有关于 API 的很好的描述,并附有示例。我正在使用标准文档,但我在寻找一些更有条理的东西。
解决方案 1:
您可以使用find_all
以下方式查找每个a
具有href
属性的元素,并打印每个元素:
# Python2
from BeautifulSoup import BeautifulSoup
html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
# The output would be:
# Found the URL: some_url
# Found the URL: another_url
# Python3
from bs4 import BeautifulSoup
html = '''<a href="https://some_url.com">next</a>
<span class="class">
<a href="https://some_other_url.com">another_url</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print("Found the URL:", a['href'])
# The output would be:
# Found the URL: https://some_url.com
# Found the URL: https://some_other_url.com
请注意,如果您使用的是旧版本的 BeautifulSoup(版本 4 之前),则此方法的名称为findAll
。在版本 4 中,BeautifulSoup 的方法名称已更改为符合 PEP 8 要求,因此您应改用find_all
。
如果您想要所有带有 的标签href
,则可以省略name
参数:
href_tags = soup.find_all(href=True)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD