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])
我想要輸出每個(gè)鏈接的網(wǎng)址,但是上面的代碼 結(jié)果是錯(cuò)誤:print (i[href])NameError: name ’href’ is not defined
問題解答
回答1:首先字典的 key 需要引號, print(i[’href’])
你可以用 print(i.get(’href’) ,防止找不到這個(gè)元素的時(shí)候報(bào) 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
給個(gè)建議:問問題的時(shí)候盡量把自己的疑問說出來。你這里主要是 i[’href’] 沒加單引號
相關(guān)文章:
1. objective-c - ios百度地圖定位問題2. html5 - 如何解決bootstrap打開模態(tài)modal窗口引起頁面抖動(dòng)?3. javascript - 求助關(guān)于js正則問題4. javascript - node.js服務(wù)端渲染解疑5. javascript - 求助這種功能有什么好點(diǎn)的插件?6. html5 - rudy編譯sass的時(shí)候有中文報(bào)錯(cuò)7. html - css 如何添加這種邊框?8. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?9. 微信開放平臺(tái) - Android調(diào)用微信分享不顯示10. javascript - 關(guān)于定時(shí)器 與 防止連續(xù)點(diǎn)擊 問題
