python - 鏈接網(wǎng)址輸出的問題
問題描述
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])
我想要輸出每個鏈接的網(wǎng)址,但是上面的代碼 結(jié)果是錯誤: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’] 沒加單引號
相關(guān)文章:
1. java - c++ 經(jīng)常出現(xiàn)error LNK20192. 語法錯誤,意外’:’3. mysql 為什么主鍵 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?4. 我的怎么不顯示啊,話說有沒有QQ群什么的5. wordpress里,這樣的目錄列表是屬于小工具還是啥?6. 常量在外面不加引號會報錯。7. 一直報這個錯誤8. mysql federated引擎無法開啟9. sublime text3安裝package control失敗10. mysql - 大部分?jǐn)?shù)據(jù)沒有行溢出的text字段是否需要拆表
