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. mysql - 在不允许改动数据表的情况下,如何优化以varchar格式存储的时间的比较?2. css - chrome下a标签嵌套img 显示会多个小箭头?3. css3 - 纯css实现点击特效4. docker网络端口映射,没有方便点的操作方法么?5. java中返回一个对象,和输出对像的值,意义在哪儿6. mysql 为什么主键 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?7. vim - docker中新的ubuntu12.04镜像,运行vi提示,找不到命名.8. javascript - 有适合开发手机端Html5网页小游戏的前端框架吗?9. javascript - Img.complete和img.onload判断图片加载完成有什么区别?10. 推薦好用mysql管理工具?for mac和pc
