使用python格式下载文件无效

2024-09-27 21:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我正试着从印度nse网站下载股票数据

所以我用python来做这个

链接是

 import urllib
   urllib.urlretrieve("https://www.nseindia.com/content/historical/DERIVATIVES/2016/JAN/fo01JAN2016bhav.csv.zip","fo01JAN2016bhav.csv.zip")

但是当我试图打开下载的文件时,它显示

^{pr2}$

当我尝试从网站正常下载时,只要粘贴链接,下载的文件就会打开

链接

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下载图片,代码运行良好

当我可以通过浏览器正常访问时,为什么会出现http403错误?在


Tags: csvinpyhttpscomlibwwwline
2条回答

嘿,我不知道为什么在urllib和urllib2库中会发生这种情况,但是当我使用请求库时

r = requests.get(url)
with open("code3.zip", "wb") as code:
    code.write(r.content)

成功了

这可能是我答案的间接解决方案

此链接提供了一个您要执行的操作的示例: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文件无效

相关问题 更多 >

    热门问题