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. word-wrap该如何使用?2. javascript - CSS图片轮播显示问题3. python - 有什么好的可以收集货币基金的资源?4. MySQL的SELECT...FOR UPDATE究竟起什么作用5. mysql 怎么做到update只更新一行数据?6. mysql - 要取出数据库中按某字段排序后的前10,20,30条数据要怎么做?7. windows-7 - win7下使用cmder,如何设置vim的tab为4个空格?8. python - 怎么进行服务器性能分析9. thinkPHP5中获取数据库数据后默认选中下拉框的值,传递到后台消失不见。有图有代码,希望有人帮忙10. python 多进程 或者 多线程下如何高效的同步数据?

网公网安备