Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str
在python的Beautiful Soup 4 扩展库的使用过程中出现了
TypeError: list indices must be integers or slices, not str
这个错误,这里就分析一下为什么会报错以及如何解决。
这个错误的意思是'类型错误:list的索引必须是'integers'或者'slices'不能是'str'
我出现错误的代码:
#引入库 from bs4 import BeautifulSoup #读取页面 soup = BeautifulSoup(open('index.html')) #获取标签 img_tag = div.select("img") #获取标签属性(这里报错) src = img_tag['src'] #输出 print(src)
经过检查对比后我发现错误原因
就是获取标签时获取的是list数据而不是tag
主要原因如下:
主要就是获取的内容和自己认为的有偏差。
也就是find()和find_all(),select()和select_one()的区别。
当使用
find() select_one()
时,获得的是一个标签
类型为
<class 'bs4.element.Tag'>
所以可以使用tag['class']取值
当使用
find_all() select()
时,获得的是组标签(就算只有一个标签也是一组)
类型为
#find_all()的返回值类型 <class 'bs4.element.ResultSet'> #select()的返回值类型 <class 'list'>
这时,我们要取值就需要先定位是list(ResultSet)中的那个标签在取值
例如tag[0]['class']
解决方法
方法一:
#引入库 from bs4 import BeautifulSoup #读取页面 soup = BeautifulSoup(open('index.html')) #获取标签 img_tag = div.select("img") #获取标签属性(这里有改动) src = img_tag[0]['src'] #输出 print(src)
因为我知道页面中的结构可以确保获得的第一个bag为我需要的标签。
所以使用src = img_tag[0]['src']来获取属性信息。
方法二:
#引入库 from bs4 import BeautifulSoup #读取页面 soup = BeautifulSoup(open('index.html')) #获取标签 img_tag = div.select_one("img") #获取标签属性(这里有改动) src = img_tag['src'] #输出 print(src)
同上理,这样修改也是可以成功的。
出现这种问题还是因为自己不用心,还是要时刻提醒自己。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
- python BeautifulSoup使用方法详解
- Python BeautifulSoup中文乱码问题的2种解决方法
- python 解析html之BeautifulSoup
- Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释
- python中bs4.BeautifulSoup的基本用法
- python基于BeautifulSoup实现抓取网页指定内容的方法
- Python使用BeautifulSoup库解析HTML基本使用教程
- python爬虫之BeautifulSoup 使用select方法详解
- python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
- 从零开始学习Python与BeautifulSoup网页数据抓取
相关文章
Python 中 Pandas 文件操作和读取 CSV 参数详解
CSV 又称逗号分隔值文件,是一种简单的文件格式,以特定的结构来排列表格数据,这篇文章主要介绍了Python 之 Pandas 文件操作和读取 CSV 参数详解,需要的朋友可以参考下2023-03-03python GoogleIt库实现在Google搜索引擎上快速搜索
这篇文章主要为大家介绍了python GoogleIt库实现在Google搜索引擎上快速搜索功能探究,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2024-01-01Python UnicodeEncodeError: ''gbk'' codec can''t encode chara
这篇文章主要介绍了Python UnicodeEncodeError: 'gbk' codec can't encode character 解决方法,需要的朋友可以参考下2015-04-04
最新评论