我有以下内容soup
:
<a href="some_url">next</a>
<span class="class">...</span>
我想从中提取 href,"some_url"
如果我只有一个标签就可以做到,但这里有两个标签。我也能得到文字'next'
但这不是我想要的。
另外,是否有关于 API 的详细描述和示例。我在用着标准文档 http://www.crummy.com/software/BeautifulSoup/documentation.html,但我正在寻找更有组织性的东西。
您可以使用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 http://www.crummy.com/software/BeautifulSoup/bs4/doc/#method-names,所以你应该使用find_all
反而。
如果你想all带有一个标签href
,你可以省略name
范围:
href_tags = soup.find_all(href=True)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)