首页 > 解决方案 > 使用 Python 请求模块下载的文件引发无效文件错误

问题描述

我有以下从 URL 下载 zip 文件的代码。我使用了 Python 的 requests 模块。

对于 URL =“https://www1.nseindia.com/content/historical/DERIVATIVES/2018/OCT/fo23OCT2018bhav.csv.zip”,代码返回 557KB 的 zip 文件。

但是,对于 URL =“https://www1.nseindia.com/content/historical/DERIVATIVES/2015/OCT/fo23OCT2015bhav.csv.zip”,代码返回 1KB 的 zip 文件。在尝试打开这个 1KB 的文件时,它会抛出错误“Windows 无法打开文件夹。压缩(压缩)文件夹无效。”

显然,当我尝试使用 URL = "https://www1.nseindia.com/content/historical/DERIVATIVES/2015/OCT/fo23OCT2015bhav.csv.zip") 的浏览器下载文件时,它会下载一个 341KB 的文件.

使用浏览器有效的方法不适用于 python 代码。

这是可以导航和下载数据的 URL:

https://www1.nseindia.com/products/content/derivatives/equities/archieve_fo.htm 一个选择报告 = Bhavcopy 和日期为 23-10-2015

我在代码中遗漏了什么吗?

感谢您在这方面的帮助。

谢谢,

import os
import time
import datetime
import requests
from zipfile import ZipFile
from random import choice

desktop_agents = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36 Edg/86.0.622.48']

def random_headers():
    return {'User-Agent': choice(desktop_agents),'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}

today = datetime.date(2015,10,23)
#today = datetime.date(2018,10,23)

date=today.strftime('%d')
month=today.strftime('%b').upper()
year=today.strftime('%Y')

url="https://www1.nseindia.com/content/historical/DERIVATIVES/2015/OCT/fo23OCT2015bhav.csv.zip"
#url="https://www1.nseindia.com/content/historical/DERIVATIVES/2018/OCT/fo23OCT2018bhav.csv.zip"

#url = "https://www1.nseindia.com/content/historical/DERIVATIVES/" + year + "/" + month + "/" + "fo" + date + month + year + "bhav.csv.zip"
folder = "C:\\Temporary\\"
filename1 = folder + "fo" + date + month + year + "bhav.csv.zip"

print(url)

req = requests.get(url, allow_redirects=True, headers=random_headers())
file= open(filename1,'wb').write(req.content)

通过手动导航获得的网站图像

标签: pythonpython-requests

解决方案


推荐阅读