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 - 数组原声方法中的一段代码2. python小白的基础问题 关于while循环的嵌套3. MySQL客户端吃掉了SQL注解?4. javascript - JS设置Video视频对象的currentTime时出现了问题,IE,Edge,火狐,都可以设置,反而chrom却...5. 求大神帮我看看是哪里写错了 感谢细心解答6. javascript - 百度echarts series数据更新问题7. python - Django分页和查询参数的问题8. javascript - 图片能在网站显示,但控制台仍旧报错403 (Forbidden)9. php自学从哪里开始?10. phpstady在win10上运行
