关于Python一直提示IndexError: list index out of range是怎么回事?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Python一直提示IndexError: list index out of range是怎么回事?相关的知识,希望对你有一定的参考价值。

如下源码:
# -*- coding: utf-8 -*-

import time
import re
from start.loan import Loan
from scrapy.spider import Spider
from scrapy.selector import Selector

from start.items import LoanItem

class hepaiSpider(Spider):
name = "hepai"
allowed_domains = ["he-pai.cn"]
start_urls = [
"http://www.he-pai.cn/investmentDetail/investmentDetails/index.do"
]

def parse(self, response):
sel = Selector(response)
items = []
loan =Loan()
sites = sel.xpath("//div[@class='tabs_con']")
for site in sites:
item = LoanItem()
item['company_name'] = '合拍在线'
item['title'] = site.xpath("table/tbody/tr/a/text()").extract()[0]
# item['link'] = u'http://www.he-pai.cn' + site.xpath
item['rate'] = site.xpath("table/tbody/tr/td[2]/text()").extract()[0]
item['rate'] = loan.scanNumber(item['rate'],False)
item['amount'] = site.xpath("table/tboday/td[3]/text()").extract()[0]
item['amount'] = loan.scanNumber(item['amount'])
item['public_time'] = site.xpath("table/tbody/td[4]/text()").extract()[0]
item['public_time'] = loan.scanNumber(item['public_time'])
item['process'] = site.xpath("table/tbody/td[5]/div/div[1]/@style").extract()[0]
item['process'] = loan.scanNumber(item['process'])
item['period'] = site.xpath("table/tbody/td[6]/text()").extract()[0]
item['period_type'] = loan.scanNumber(item['period'])
items.append(item)
return items;
这是全部的错误提示

File "/home/yx/sites/scrapy/start/start/spiders/hepai_spider.py", line 26, in parse
item['title'] = site.xpath("table/tbody/tr/a/text()").extract()[0]

exceptions.IndexError: list index out of range
求指教啊。。。

”IndexError: list index out of range”这种错误一般有两种情况:

第一种可能情况:list[index], index超出范围,也就是常说的数组越界。

第二种可能情况:list是一个空的,没有一个元素,进行list[0]就会出现该错误,在爬虫问题中很常见,比如有个列表爬去下来为空,统一处理就会报错。

扩展资料:

异常处理特点:

1.在应用程序遇到异常情况(如被零除情况或内存不足警告)时,就会产生异常。

2.发生异常时,控制流立即跳转到关联的异常处理程序(如果存在)。

3.如果给定异常没有异常处理程序,则程序将停止执行,并显示一条错误信息。

4.可能导致异常的操作通过 try 关键字来执行。

5.异常处理程序是在异常发生时执行的代码块。在 C# 中,catch 关键字用于定义异常处理程序。

6.程序可以使用 throw 关键字显式地引发异常。

7.异常对象包含有关错误的详细信息,其中包括调用堆栈的状态以及有关错误的文本说明。

8.即使引发了异常,finally 块中的代码也会执行,从而使程序可以释放资源。

参考资料:百度百科——异常处理

参考技术A 错误提示是数组调用超出范围了
extract()后边带个【0】是什么意思?代码是自己写的吗?
还有item数组用之前给个定义追问

额,代码不是自己写的,是参照其他人的修改的,我是Python新手,公司实习让做这个,我把extract后面的0去掉后不出错了,但是也爬不到数据,显示爬到的title之类的都是【】,没有数据求大神指教

追答

爬不到数据检查下你的数据,可能是数据的问题,代码应该没什么问题了

追问

好的,大神,可以给我推荐一下怎么学吗?像我这种零基础要做事的情况?

追答

是python零基础么?这样的话最好先找一本基础的书(百度python基础书籍,随便找一本看就行,主要是看完对python有个初步认识,耐心点儿),认识一下python的语言逻辑及语法结构,然后就是多看程序代码实例就行。

本回答被提问者采纳
参考技术B 列表索引超出范围

IndexError:元组索引超出范围 ----- Python

【中文标题】IndexError:元组索引超出范围 ----- Python【英文标题】:IndexError: tuple index out of range ----- Python 【发布时间】:2013-12-16 06:22:47 【问题描述】:

请帮助我。我正在运行一个简单的 python 程序,它将以 tkinter 形式显示来自 mySQL 数据库的数据...

from Tkinter import *
import MySQLdb

def button_click():
    root.destroy()

root = Tk()
root.geometry("600x500+10+10")
root.title("Ariba")

myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)

db = MySQLdb.connect ("localhost","root","","chocoholics")
s = "Select * from member"
cursor = db.cursor()
cursor.execute(s)
rows = cursor.fetchall()

x = rows[1][1] + " " + rows[1][2]
myLabel1 = Label(myContainer, text = x)
y = rows[2][1] + " " + rows[2][2]
myLabel2 = Label(myContainer, text = y)
btn = Button(myContainer, text = "Quit", command=button_click, height=1, width=6)

myLabel1.pack(side=TOP, expand=NO, fill=BOTH)
myLabel2.pack(side=TOP, expand=NO, fill=BOTH)
btn.pack(side=TOP, expand=YES, fill=NONE)

这就是整个程序......

错误是

x = rows[1][1] + " " + rows[1][2]
IndexError: tuple index out of range

y = rows[2][1] + " " + rows[2][2]
IndexError: tuple index out of range

谁能帮帮我???我是python新手。

非常感谢……

【问题讨论】:

表示你访问的索引(位置)不存在。 我将用什么代码替换我现有的代码???谢谢 我不知道;你能提供一个small self-contained reproducible example 并编辑你的问题以包含它吗? 您应该尝试使用 print(rows) 和 print(rows[1]) 来查看您的数据是什么样的。它可以帮助您找到问题。 当我将 train_sizes=np.linspace(0.1, 1.0, 10) 更改为 train_sizes=10 时出现此错误 【参考方案1】:

我收到与 query = "INSERT INTO table(field1, field2,...) VALUES (%s,%s,...)" 相同的错误 但在声明中cursor.execute(query, (field1, field2,..) 我根据需要提供了更少的变量... 在这种情况下,我使用了

import mysql.connector as mysql 

我只是想说这也是可能的......不仅在数组中 (我没有仔细研究这个具体案例......)

【讨论】:

【参考方案2】:

可能其中一个索引是错误的,无论是内部索引还是外部索引。

我怀疑你的意思是说[0],你说的是[1],和[1],你说的是[2]。 Python 中的索引从 0 开始。

【讨论】:

我收到这条消息是因为我将一个数组传递给一个期望可变参数序列的函数(例如''.format([1,2]) vs ''.format(*[1,2]) 另一种情况是字符串中有两个“”,而 .format() 中只有一个变量/值 如果您在参数列表中有一个放错位置的赋值运算符 (=),这是另一个原因。我已经改组了一些代码并结束了。 ...作为 Dror 评论的变体:在格式字符串中包含 而不是 。当有人想要从字面上打印一对花括号时,这是一个典型的复制粘贴错误。 我也遇到同样的错误,你能查一下***.com/questions/46945860/…【参考方案3】:

格式化函数

此错误可能发生在 format() 函数行中。 在你的机器上试试下面的代码

>>> 'This is just a string '.format()

请注意发生此错误。但是,因为使用了尖括号,所以没有 参数被传递给format()。在 Python 术语中,

参数的数量必须与花括号的数量匹配或更高。

在下面几个例子不被认为是好的做法,但就 Python3 而言可能没有错误。

>>> 'This is just a string'.format()  # No curly braces no arguments. Match in proportion.
>>> 'This is just a string '.format('WYSIWYG', 'J. Pinkman', 'ESR')  # The number of arguments is superior to the number of curlies( *curly braces* ).

【讨论】:

【参考方案4】:

元组由许多用逗号分隔的值组成。喜欢

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

元组在 Python 中是基于索引的(也是不可变的)。

在这种情况下,x = rows[1][1] + " " + rows[1][2] 只有两个索引 0、1 可用,但您正在尝试访问第三个索引。

【讨论】:

【参考方案5】:

这是因为您的 row 变量/元组不包含该索引的任何值。您可以尝试打印整个列表,例如 print(row),并检查存在多少索引。

【讨论】:

好建议...帮助了我。

以上是关于关于Python一直提示IndexError: list index out of range是怎么回事?的主要内容,如果未能解决你的问题,请参考以下文章

findspark.init() IndexError: 列表索引超出范围错误

Python:IndexError:列表索引超出范围 Caeser Cipher

Python - 警告:意外错误:<class 'IndexError'>

IndexError:列表索引超出范围(Python)

Python 3.6“IndexError:列表索引超出范围”

Python:IndexError:列表索引超出范围