Python模块BeautifulSoup提取锚HREF [英] Python module BeautifulSoup extracting anchors href

查看:829
本文介绍了Python模块BeautifulSoup提取锚HREF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用BeautifulSoup模块通过这种方式来选择所有的HTML HREF:

 高清extract_links(HTML):
  汤= BeautifulSoup(HTML)
  锚= soup.findAll('A')
  打印锚
  链接= []
  对于在锚:
    links.append(一[HREF'])
  返回链接

但有时它未能通过此错误消息:

 回溯(最后最近一次调用):
文件C:\\ PY \\ main.py33行,上述<&模块GT;
网址= extract_links(页)
文件C:\\ PY \\ main.py,11号线,在extract_links
links.append(一[HREF'])
文件C:\\ PY \\ BeautifulSoup.py,线路601,在__getitem__
返回self._getAttrMap()[关键]
KeyError异常:HREF


解决方案

并非所有的锚标签将有href属性。您应检查锚有一个href您尝试访问该属性之前。

 如果a.has_key('href属性)
  links.append(一[HREF'])

在这里检查了一些意见后,我认为这是处理这种情况的最Python的方式。

i am using BeautifulSoup module to select all href from html by this way:

def extract_links(html):
  soup = BeautifulSoup(html)
  anchors = soup.findAll('a')
  print anchors
  links = []
  for a in anchors:
    links.append(a['href'])
  return links

but sometime it failed by this error message:

Traceback (most recent call last):
File "C:\py\main.py", line 33, in <module>
urls = extract_links(page)
File "C:\py\main.py", line 11, in extract_links
links.append(a['href'])
File "C:\py\BeautifulSoup.py", line 601, in __getitem__
return self._getAttrMap()[key]
KeyError: 'href'

解决方案

Not all anchor tags will have an href attribute. You should check that the anchor has an href before you try to access that attribute.

if a.has_key('href')
  links.append(a['href'])

After checking some comments here, I think this is the most pythonic way of handling this case.

这篇关于Python模块BeautifulSoup提取锚HREF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆