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’] 沒加單引號
相關文章:
1. HTML5禁止img預覽該怎么解決?2. javascript - vue+iview upload傳參失敗 跨域問題后臺已經(jīng)解決 仍然報403,這是怎么回事啊?3. python - django 按日歸檔統(tǒng)計訂單求解4. objective-c - 從朋友圈跳到我的APP 如何實現(xiàn)?5. 百度地圖api - Android 百度地圖 集成了定位,導航 相互的jar包有沖突?6. 網(wǎng)頁爬蟲 - python爬蟲用BeautifulSoup爬取<s>元素并寫入字典,但某些div下沒有這一元素,導致自動寫入下一條,如何解決?7. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。8. 請教一個python字符串處理的問題?9. sql語句 - mysql中關聯(lián)表查詢問題10. 怎么可以實現(xiàn)在手機瀏覽器看到鏈接的title屬性,就是鼠標放上去會有一個tip效果的
