【问题标题】:How to extract a href link from anchor tags in beautiful soup [duplicate]如何从美丽汤中的锚标签中提取href链接[重复]
【发布时间】:2012-07-16 10:39:56
【问题描述】:

可能重复:
BeautifulSoup getting href

我用的是漂亮的汤,下面是我的代码

import urllib2
data = urllib2.urlopen("some_url")
html_data = data.read()
soup = BeautifulSoup(html_data)
href_tags = soup.findAll('a')

结果:

href_tags = 
[<a href="http://www.exampl.com/score_card" target="_blank" style="font-family:arial;color:#192e94;">Click Here</a>, 
<a href="https://example.icims.com/jobs/search?pr=5">what is this</a>,
<a href="https://example.com/search?pr=6">Cool</a>,
<a href="https://example.com/help/host/search?pr=7">Hello</a>]

但实际上我想从所有锚标签中提取href,我该如何提取href标签。

提前致谢…………

【问题讨论】:

标签: python url beautifulsoup href urllib2


【解决方案1】:

在我的脑海中 - href_tags = [tag['href'] for tag in soup.findAll('a', {'href': True})]

{'href': True} 确保有一个 href 属性,这样tag.attr['href'] 就不会失败。

【讨论】:

    【解决方案2】:

    尝试循环匹配:

    import urllib2
    data = urllib2.urlopen("some_url")
    html_data = data.read()
    soup = BeautifulSoup(html_data)
    
    for a in soup.findAll('a',href=True):
        print a['href']
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2020-03-17
      • 2015-08-01
      • 2018-07-31
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多