无法将网址放入列表(BeautifulSoup)

问题描述:

我想提取所有的网址,并将所有这些网址放入列表中。但是,当我运行代码时,它显示一条错误消息:"tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there."我想知道如何解决此问题。 我的代码如下:无法将网址放入列表(BeautifulSoup)

import urllib.request 
from bs4 import BeautifulSoup 

r = 'https://stackoverflow.com/' 
openedUrl = urllib.request.urlopen(r) 

soup = BeautifulSoup(openedUrl, 'lxml') 

aa = soup.find_all('a') 
href = [] 
for a in aa: 
    href.append(a['href']) 

print(href) 

的问题是,一些“A”标签不具有“HREF”属性,所以Python会抛出一个异常KeyError当您尝试访问a['href']

如果将关键字参数href设置为True,则可以避免这种情况。

aa = soup.find_all('a', href=True) 

当访问键从标签属性,最好使用get方法,因为它如果该键不存在,所以它不会引发异常返回None

+1

它的工作原理。非常感谢! – tzu