我正在使用BeautifulSoup模块按以下方式选择HTML中的所有href链接:
def extract_links(html):
soup = BeautifulSoup(html)
anchors = soup.findAll('a')
print anchors
links = []
for a in anchors:
links.append(a['href'])
return links
但有时会出现以下错误信息导致失败:
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'
href
属性的a
标签。与其要求字典提供可能具有href
属性的标签,不如在将数据放入字典之前先询问数据是否具有该属性。 - yurisichkeys
不是你期望的。 - Thomas K