Python 3.6.5 urllib.error.HTTPError:HTTP错误403:禁止

时间:2018-07-14 06:15:35

标签: python-3.6

我正在尝试从互联网下载csv文件。这是我使用urllib的代码。但我收到HTTP错误403。

程序1:

from urllib import request
nse_stocks = 'https://www.nseindia.com/products/content/sec_bhavdata_full.csv'

def download_file(url):
    connection = request.urlopen(url)
    file_read = connection.read()
    file_str = str(file_read)
    lines_file_str = file_str.split('\\n')
    file = open(r'downloaded_file.csv', 'w')
    for line in lines_file_str:
        file.write(line + '\n')
    file.close()
download_file(nse_stocks)

回复:

Traceback (most recent call last):
  File "C:/Users/sg0205481/Documents/Krishna/eBooks/Python/TheNewBoston/Python/downloadWebFile2.py", line 17, in <module>
    download_file(nse_stocks)
  File "C:/Users/sg0205481/Documents/Krishna/eBooks/Python/TheNewBoston/Python/downloadWebFile2.py", line 7, in download_file
    connection = request.urlopen(url)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Users\sg0205481\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

但是我没有收到带有请求模块的Program-2的错误。文件已成功下载。

程序2:

import requests

def download_file(url):
    file_data = requests.get(url)
    filename = 'downloaded_file.csv'
    with open(filename, 'wb') as file:
        file.write(file_data.content)


download_file('https://www.nseindia.com/products/content/sec_bhavdata_full.csv')

程序1有什么问题?是什么让Program-2成功通过?

1 个答案:

答案 0 :(得分:0)

您可以从Web服务器使用get方法而不是post方法下载文件(MIME类型)。如果Web服务器具有此扩展程序的处理程序并接受post方法,则可以尝试!!!