【问题标题】:Beautiful Soup - how to get href美丽的汤 - 如何获得href
【发布时间】:2011-11-15 08:07:42
【问题描述】:

我似乎无法从以下html汤中提取href(页面上只有一个<strong>Website:</strong>):

<div id='id_Website'>
<strong>Website:</strong> 
<a href='http://google.com' target='_blank' rel='nofollow'>www.google.com</a>
</div></div><div>

这是我认为应该起作用的

href = soup.find("strong" ,text=re.compile(r'Website')).next["href"]

【问题讨论】:

    标签: beautifulsoup


    【解决方案1】:

    .next 在这种情况下是一个NavigableString,包含&lt;strong&gt; 标记和&lt;a&gt; 标记之间的空格。此外,text= 属性用于匹配 NavigableStrings,而不是元素。

    我认为以下内容可以满足您的需求:

    import re
    from BeautifulSoup import BeautifulSoup
    
    html = '''<div id='id_Website'>
    <strong>Website:</strong> 
    <a href='http://google.com' target='_blank' rel='nofollow'>www.google.com</a>
    </div></div><div>'''
    
    soup = BeautifulSoup(html)
    
    for t in soup.findAll(text=re.compile(r'Website:')):
        # Find the parent of the NavigableString, and see
        # whether that's a <strong>:
        s = t.parent
        if s.name == 'strong':
            print s.nextSibling.nextSibling['href']
    

    ...但这不是很健壮。如果封闭的div 有一个可预测的ID,那么最好找到它,然后在其中找到第一个&lt;a&gt; 元素。

    【讨论】:

    • 这就是我想要的。谢谢你。如何按 ID 搜索以获得下一个 href 值?
    • 您可以使用 soup.findAll('div', id=re.compile('Website$')) 之类的东西来让所有 divs 考虑 - 虽然没有看到其他示例,但不清楚您将如何挑选它们。
    猜你喜欢
    • 2018-05-08
    • 2016-12-18
    • 2019-04-14
    • 2018-07-31
    • 2018-09-04
    • 2010-11-06
    • 2021-09-23
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多