[英]downloading file using python format becomes invalid
嘿,我试图从印度的NSE网站下载股票数据
所以我为此使用python
链接是
import urllib
urllib.urlretrieve("https://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip","fo01JAN2016bhav.csv.zip")
但是当我尝试打开下载的文件时,它说
compressed zipped file is invalid
当我尝试通过简单地粘贴链接从网站正常下载时,被下载的文件就会打开
链接
https://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip
所以如果我尝试使用urllib 2我会得到这个
f=urllib2.urlopen('https://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
f=urllib2.urlopen('https://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip')
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden
我该如何解决 ?
仅在我尝试从imgur下载图像且代码正常工作时,此链接才会发生
当我通常可以通过浏览器访问它时,为什么会出现HTTP 403错误?
此链接提供了您要执行的操作的示例: https : //stackoverflow.com/a/22776/6595777
找到了另一个有关下载zip文件的问题。 尝试这个:
url = "http://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip"
download = urllib2.urlopen(url)
with open(os.path.basename(url), "wb") as f:
f.write(download.read())
我还没有评论权限,所以我将其发布为答案。 我无法通过https浏览到您的链接,但是http可以。 您是否尝试过将脚本中的链接更改为http?
您的脚本可能正在下载尝试使用https时出现的错误页面( ERR_SSL_PROTOCOL_ERROR
。)这意味着您下载的文件将具有您指定的文件名(以.zip
结尾),但实际上是html。 这意味着它将给您以下错误:zip文件无效
嘿,我不知道为什么这在urllib和urllib2库中发生,但是当我使用请求库时
r = requests.get(url)
with open("code3.zip", "wb") as code:
code.write(r.content)
有效
这可能是我答案的间接解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.