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 - 关于定时器 与 防止连续点击 问题2. javascript - 求助关于js正则问题3. objective-c - ios百度地图定位问题4. javascript - 求助这种功能有什么好点的插件?5. javascript - js 有什么优雅的办法实现在同时打开的两个标签页间相互通信?6. 为何 localStorage、sessionStorage 属于html5的范畴,但是为何 IE8却支持?7. html5 - rudy编译sass的时候有中文报错8. html - css 如何添加这种边框?9. javascript - node.js服务端渲染解疑10. 微信开放平台 - Android调用微信分享不显示
