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. javascript - 循環嵌套多個promise應該如何實現?2. mysql優化 - 關于mysql分區3. css3 - rem布局下,用戶瀏覽器的最小字號是12px怎么辦?4. javascript - ionic2 input autofocus 電腦成功,iOS手機鍵盤不彈出5. html5 - 如何實現帶陰影的不規則容器?6. objective-c - iOS開發支付寶和微信支付完成為什么跳轉到了之前開發的一個app?7. 前端 - IE9 css兼容問題8. 請教各位大佬,瀏覽器點 提交實例為什么沒有反應9. vue.js - vue 打包后 nginx 服務端API請求跨域問題無法解決。10. css - 移動端字體設置問題
