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. html5 - HTML代碼中的文字亂碼是怎么回事?2. 解決Android webview設置cookie和cookie丟失的問題3. javascript - nodejs使用mongoose連接數據庫,使用post提交表單在后臺,后臺處理后調用res.redirect()跳轉界面無效?4. javascript - 能否讓vue-cli的express修改express重啟服務5. javascript - vue2如何獲取v-model變量名6. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題7. javascript - 求幫助 , ATOM不顯示界面!!!!8. html5 - 急求?被公司問住了9. javascript - vue2.0中,$refs對象為什么用駝峰的方式獲取不到屬性?10. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?
