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. 運行python程序時出現“應用程序發生異常”的內存錯誤?2. 在mac下出現了兩個docker環境3. 利用IPMI遠程安裝centos報錯!4. spring-mvc - spring-session-redis HttpSessionListener失效5. javascript - QQ第三方登錄的問題6. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]7. javascript - node得到req不能得到boolean8. javascript - 最近用echarts做統計圖時遇到兩個問題!!9. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統有創建日志文件,不寫入日志信息。10. javascript - 在 model里定義的 引用表模型時,model為undefined。

網公網安備