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. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下2. redux单页面应用中 是一个store?3. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””4. javascript - 在vue-cli引入vux后 使用报错5. debian - docker依赖的aufs-tools源码哪里可以找到啊?6. java - struts2找不到类文件7. 图片上传成功但数据库字段是空8. javascript - SuperSlide.js火狐不兼容怎么回事呢9. python - 在sqlalchemy中获取刚插入的数据id?10. javascript - js代码转python

网公网安备