本文介绍了预定义发生预期错误时要采取的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 您好。我收到下面显示的错误,我知道 究竟是为什么会发生。我在下面发布了一些我的程序代码,如果你看了它,你会看到错误终止程序 。由于这个预成熟终止,该程序是无法执行它的最后一行代码,这是一个非常重要的行。最后一行保存Excel电子表格。那么有没有办法让确保最后一行执行?感谢先进的所有 帮助。谢谢。 错误 #### IndexError:列表索引超出范围 代码示例 ########### for rx in range(sh.nrows): rx = rx +1 u = sh.cell_value(rx,0) u = str(u) if u!= end : page = urllib2.urlopen(u) 汤= BeautifulSoup(页) p = soup.findAll(''span'', " sale") p = str(p) p2 = re.findall(''\ $ \d + \。\\\' ',p) $ p $ b for p2行: ws.write(r,0,row) w.save (''price_list.xls'') Hello. I am getting the error that is displayed below, and I knowexactly why it occurs. I posted some of my program''s code below, and ifyou look at it you will see that the error terminates the programpre-maturely. Becasue of this pre-mature termination, the program isnot able to execute it''s final line of code, which is a very importantline. The last line saves the Excel spreadsheet. So is there a way tomake sure the last line executes? Thanks in advanced for all of thehelp. Thank you.Error#### IndexError: list index out of rangeCode Sample########### for rx in range(sh.nrows):rx = rx +1u = sh.cell_value(rx, 0)u = str(u)if u != end:page = urllib2.urlopen(u)soup = BeautifulSoup(page)p = soup.findAll(''span'', "sale")p = str(p)p2 = re.findall(''\$\d+\.\d\d'', p)for row in p2:ws.write(r,0,row) w.save(''price_list.xls'') 推荐答案 两种方法: (1)修复错误,使程序不再提前终止。你得到了一个IndexError" list index out of range",所以修复程序使得没有 更长时间尝试访问超出列表末尾。 我猜测你的错误在循环开始时是正确的。你好b / b 说: rx范围内的(sh.nrows): rx = rx +1 为什么要在循环变量中添加一个?这相当于: 范围内的rx(1,sh.nrows + 1) 这可能意味着它会跳过行0并尝试访问超过 结尾的一行。如果您想要做的只是跳过第0行,请改为: 表示范围内的rx(1,sh.nrows) (2)Stick试试看错误的创可贴...除了阻止,希望 你也没有掩盖其他错误。虽然我们正在使用它,但是让我们的b $ b重构一下代码... #未经测试 def write_row(rx,sh,end,ws): u = str(sh.cell_value(rx,0)) if u!= end: 汤= BeautifulSoup(urllib2.urlopen(u)) p = str(soup.findAll(''span'','sale")) 表示re.findall中的行(''\ Two methods: (1) Fix the bug so the program no longer terminates early. You are gettingan IndexError "list index out of range", so fix the program so it nolonger tries to access beyond the end of the list. I''m guessing that your error is right at the beginning of the loop. Yousay: for rx in range(sh.nrows):rx = rx +1 Why are you adding one to the loop variable? That''s equivalent to: for rx in range(1, sh.nrows + 1) which probably means it skips row 0 and tries to access one row past theend of sh. If all you want to do is skip row 0, do this instead: for rx in range(1, sh.nrows)(2) Stick a band-aid over the error with a try...except block, and hopeyou aren''t covering up other errors as well. While we''re at it, let''srefactor the code a little bit... # untesteddef write_row(rx, sh, end, ws):u = str(sh.cell_value(rx, 0))if u != end:soup = BeautifulSoup(urllib2.urlopen(u))p = str(soup.findAll(''span'', "sale"))for row in re.findall(''\ 这篇关于预定义发生预期错误时要采取的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-31 14:34