这篇文章主要介绍了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[