2017-09-02 46 views
1

我想提取所有的網址,並將所有這些網址放入列表中。但是,當我運行代碼時,它顯示一條錯誤消息:"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) 

回答

1

的問題是,一些「A」標籤不具有「HREF」屬性,所以Python會拋出一個異常KeyError當您嘗試訪問a['href']

如果將關鍵字參數href設置爲True,則可以避免這種情況。

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

當訪問鍵從標籤屬性,最好使用get方法,因爲它如果該鍵不存在,所以它不會引發異常返回None

+1

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