使用Python请求模块下载的文件抛出无效文件错误

使用Python请求模块下载的文件抛出无效文件错误,python,python-requests,Python,Python Requests,我有以下代码从URL下载zip文件。我使用了Python的请求模块 对于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,

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

对于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:

其中一份选择报告=Bhavcopy,日期为2015年10月23日

我在代码中遗漏了什么吗

感谢你在这方面的帮助

谢谢

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)

当我点击链接时,访问被拒绝。对吗?当我点击链接时,它会下载一个341KB的zip文件。对于不同的用户,链接和对链接的访问是否会表现出不同的行为?@lenmet是的,在不同的情况下,行为会发生变化,在请求会话中使用浏览器cookie可能会有帮助。这种行为与访问它的区域有关,或者与用户代理有关。你能试试2018年的其他网址吗?这是否也会导致访问被拒绝错误?我在代码中指定了用户代理,以避免“拒绝访问”或其他问题。我已经包含了一个URL,用户可以通过该URL手动导航和下载2015-10-23的日期,并且可以正常工作。它不能通过代码工作的原因是什么?