【问题标题】:Python requests giving errror: IndexError: list index out of rangePython 请求给出错误:IndexError: list index out of range
【发布时间】:2017-05-17 07:03:12
【问题描述】:

Python 请求给出错误:IndexError: list index out of range:

import os
import csv
import requests

write_path = '/Users/specter/Desktop/pdfs/u'  # ASSUMING THAT FOLDER EXISTS!

with open('final.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile)
    for link in spamreader:
        print('-'*72)
        pdf_file = link[0].split('/')[-1]
    with open(os.path.join(write_path, pdf_file), 'wb') as pdf:
        try:
            # Try to request PDF from URL
            print('TRYING {}...'.format(link[0]))
            a = requests.get(link[0], stream=True)
            for block in a.iter_content(512):
                if not block:
                    break

                pdf.write(block)
            print('OK.')
        except requests.exceptions.RequestException as e:  # This will catch ONLY Requests exceptions
            print('REQUESTS ERROR:')
            print(e)  # This should tell you more details about the error

在尝试使用 python 中的请求包下载 1000 多个 pdf 文件时。

Traceback (most recent call last):
  File "update.py", line 11, in <module>
    pdf_file = link[0].split('/')[-1] 
IndexError: list index out of range

【问题讨论】:

  • 请将错误消息作为文本复制并粘贴到问题中。发布图像使帮助您变得不必要。也就是说,您尝试访问link 的第一个元素。看来,您的 link 变量可能为空。你检查过内容吗?
  • 您可以将其格式设置得更好一些(就像您对代码所做的那样),但这更好。那么,你查过link的内容了吗?也许在 link[0].split 的行之前加上一个简单的 print(link)?
  • @ChristianKönig 尝试过,但同样的错误。我是新程序员,请记住这一点:) 谢谢
  • link 是一个空序列。

标签: python web-scraping python-requests


【解决方案1】:

您的 csv 文件中可能有一些空行。在这种情况下,link 将是空字符串'',您将收到索引错误。将代码更改为:

.
.
.
with open('final.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile)
    for link in spamreader:
        if not link:
            continue
        print('-'*72)
        pdf_file = link[0].split('/')[-1]
.
.
.

进一步说明;您的代码似乎奇怪地缩进了。就目前而言,它只会打开final.csv 中的最后一个pdf。您确定不想将第二个 with 语句与其余代码一起缩进一层,以在 for 循环内执行吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 2014-10-20
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2022-10-09
    • 1970-01-01
    相关资源
    最近更新 更多