python - 鏈接網址輸出的問題
問題描述
import requestsres=requests.get(’http://news.sina.com.cn/china/’)res.encoding='utf-8'from bs4 import BeautifulSoupsoup=BeautifulSoup(res.text,’html.parser’)a=soup.select(’a’)for i in a: print (i[href])
我想要輸出每個鏈接的網址,但是上面的代碼 結果是錯誤:print (i[href])NameError: name ’href’ is not defined
問題解答
回答1:首先字典的 key 需要引號, print(i[’href’])
你可以用 print(i.get(’href’) ,防止找不到這個元素的時候報 KeyError。
https://docs.python.org/3/lib...
回答2:import requestsfrom bs4 import BeautifulSoupres = requests.get(’http://news.sina.com.cn/china/’)res.encoding = 'utf-8'soup = BeautifulSoup(res.text, ’html.parser’)a = soup.select(’a’)for i in a: try:href = i[’href’]if ’http’ in href: print(href) except KeyError:continue
給個建議:問問題的時候盡量把自己的疑問說出來。你這里主要是 i[’href’] 沒加單引號
相關文章:
1. win10 python3.5 matplotlib使用報錯2. 數組排序,并把排序后的值存入到新數組中3. html5 - css3scale和rotate同時使用轉換成matrix寫法該如何轉換?4. MySQL的聯合查詢[union]有什么實際的用處5. php多任務倒計時求助6. html - css3關于透明度的問題7. python的正則怎么同時匹配兩個不同結果?8. 默認輸出類型為json,如何輸出html9. mysql 遠程連接出錯10060,我已經設置了任意主機了。。。10. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?
