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 [解决方法] TypeError: list indices must be integers or slices, not str。因害怕失败而不敢放手一搏,永远不会成功。更多关于Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解