我有以下汤:BeautifulSoup越来越HREF
<a href="some_url">next</a>
<span class="class">...</span>
从这个我想提取的HREF,"some_url"
我能做到这一点,如果我只有一个标签,但这里有两个标签。我也可以得到文本'next'
但这不是我想要的。
此外,是否有API的例子很好的描述。我正在使用the standard documentation,但我正在寻找更有组织的东西。
我有以下汤:BeautifulSoup越来越HREF
<a href="some_url">next</a>
<span class="class">...</span>
从这个我想提取的HREF,"some_url"
我能做到这一点,如果我只有一个标签,但这里有两个标签。我也可以得到文本'next'
但这不是我想要的。
此外,是否有API的例子很好的描述。我正在使用the standard documentation,但我正在寻找更有组织的东西。
您可以通过以下方式找到一个具有href
属性每a
元素使用find_all
,并打印出每个之一:
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']
输出将是:
Found the URL: some_url
Found the URL: another_url
注意,如果您使用的是旧版本的BeautifulSoup(版本4之前),此方法的名称为findAll
。在版本4中,BeautifulSoup的方法名称为were changed to be PEP 8 compliant,因此您应该使用find_all
代替。
如果你想所有标签与href
,则可以省略name
参数:
href_tags = soup.find_all(href=True)
你可以得到与类“class =”class“” – yoshiserry 2014-05-19 01:24:34
@yoshiserry soup.find('a',{'class':'class'})''['href'] – rleelr 2017-01-08 16:15:32
你如何减弱误报和不需要的结果(即'javascript:void(0)','/ en/support/index.html','#smp-navigationList')? – user3155368 2018-02-12 10:28:29
请张贴代码示例,以显示你如何试图做到这一点 – seb 2011-04-28 08:33:04
好吧,我弄明白了: 让我感到困惑的是我使用django(html)来看它,它实际上在提交之前删除了href:汤。 find('a')变成'n'分机' – dkgirl 2011-04-28 08:38:20