在Python中进行网页抓取时“字符串索引必须是整数,而不是‘元组’”

问题描述 投票:0回答:1

错误:

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    newstr=(data1[m.start(),end])
TypeError: string indices must be integers, not 'tuple'

我正在做网页抓取。

代码:

m=re.search('<div class="read-more-content">',data1)
newstr=(data1[m.start(),(m.start()+401)])

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    newstr=(data1[m.start(),(m.start()+401)])
TypeError: string indices must be integers, not 'tuple'
end= m.start()+401
newstr=(data1[m.start(),end])
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    newstr=(data1[m.start(),end])
TypeError: string indices must be integers, not 'tuple'

尝试过但没有成功。

python
1个回答
0
投票

在Python中,要获取数组的切片,您应该使用冒号来分隔要获取的数组部分的开头和结尾。

在您的情况下,代码变为:

m = re.search('<div class="read-more-content">',data1)
newstr = (data1[m.start() : (m.start()+401)])
© www.soinside.com 2019 - 2024. All rights reserved.