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. android - 哪位大神知道java后台的api接口的对象传到前端后输入日期报错,是什么情况?求大神指点2. mac里的docker如何命令行开启呢?3. java - 在同一服务器上以不同端口启动两次同一maven项目会出错4. css - jq有无现成函数改变rotateX/Y的deg5. javascript - 如何向localStorage上的数组push数据6. java - C语言的一道算法题-兄弟郊游问题 求解?7. nginx 所有页面指向index.html8. vue添加锚点,实现滚动页面时锚点添加相应的class操作9. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?10. javascript - react-router-dom 跳转问题js
