首页 文章

BeautifulSoup得到href [重复]

提问于
浏览
138

这个问题在这里已有答案:

我有以下汤:

<a href="some_url">next</a>
<span class="class">...</span>

从这里我想提取href, "some_url"

如果我只有一个标签,我可以做到,但这里有两个标签 . 我也可以得到文字 'next' 但这不是我想要的 .

此外,是否有一个很好的描述API的例子 . 我正在使用the standard documentation,但我正在寻找一些更有条理的东西 .

1 回答

  • 209

    您可以使用 find_all 以下列方式查找具有 href 属性的每个 a 元素,并打印每个元素:

    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)
    

相关问题