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 - 关于vue-cli每次都要build才能放到线上问题。2. 大兄弟们,你们都用什么框架开发 web app3. javascript - webpack异步加载js问题4. python3.x - python连oanda的模拟交易api获取json问题第五问5. javascript - 怎么获取一个页面中的所数据,然后弄成一个json格式的字符串传给后台6. 多维数组遍历,求大佬解答???7. javascript - swiper2索引的问题8. java - Spring 定时任务如何实现每周一某个时间执行?9. javascript - 移动端 点击弹出遮罩层 加断点调试就行 不加断点就不行10. python方法调用

网公网安备