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 - node如何关闭主进程后 打开另一进程?2. 求大神指点js修改margintop导致无限下滑的问题3. 点字符“” 在MVC Web API 2中进行请求,例如api / people / STAFF.452874. shopee 开放平台 上传图片请教5. web服务器 - ubuntu下布置apache加wsgi加python6. mysql新建字段时 timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 报错7. 编辑管理员信息时,为什么没有修改过的内容会为空?8. python2.7为什么点击了"开始"按钮后,tkinter上的按钮,图中红色部分,再也点不动了?9. Mysql Begin End 语句报错10. mysql - sysbench cpu测试的结果看不懂,求解

网公网安备