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. nignx - docker內nginx 80端口被占用2. python - flask _sqlalchemy 能否用中文作為索引條件3. 關于docker下的nginx壓力測試4. java - 阿里的開發手冊中為什么禁用map來作為查詢的接受類?5. 跟蹤器怎么開啟無反應6. macos - mac下docker如何設置代理7. dockerfile - 我用docker build的時候出現下邊問題 麻煩幫我看一下8. docker api 開發的端口怎么獲取?9. dockerfile - [docker build image失敗- npm install]10. android - 百度地圖加載完成監聽
