【发布时间】: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