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. html - 移動端radio無法選中2. javascript - vue-resource如何終止之前的ajax請求?3. html5 - 在HBuilder中打包Android的apk包出錯,不知道是什么原因。4. mysql - 這條聯合sql語句哪里錯了5. mysql - 數據庫JOIN查詢6. python - 用scrapy-splash爬取網站 為啥iframe下的內容沒有被返回7. 我設置的背景怎么顯示不出來8. mysql - 數據庫建字段,默認值空和empty string有什么區別 1109. 關于Navicat連接到mysql,我改了root的密碼后,Navicat連接報錯1862?10. 正則表達式 - python pandas的sep參數問題
