Skip to main content
 首页 » 编程设计

python之HTTP 错误 401 : Authorization Required while downloading a file from HTTPS website and saving it

2025年05月04日18think

基本上我需要一个给定 URL 的程序,它下载一个文件并保存它。我知道这应该很容易,但这里有一些缺点......

首先,它是我在工作中构建的工具的一部分,除此之外我还有其他所有东西,URL 是 HTTPS,该 URL 是您粘贴到浏览器中的那些,您会看到一个弹出窗口说如果您想打开或保存文件 (.txt)。

其次,我是这方面的初学者,所以如果有我没有提供的信息,请问我。 :)

顺便说一句,我正在使用 Python 3.3。

我试过这个:

import urllib.request 
response = urllib.request.urlopen('https://websitewithfile.com') 
txt = response.read() 
print(txt) 

然后我得到:

urllib.error.HTTPError: HTTP Error 401: Authorization Required 

有什么想法吗?谢谢!!

请您参考如下方法:

您可以使用请求库轻松地做到这一点。

import requests 
response = requests.get('https://websitewithfile.com/text.txt',verify=False, auth=('user', 'pass')) 
print(response.text) 

保存你要输入的文件

with open('filename.txt','w') as fout: 
   fout.write(response.text): 

(我建议您始终在 resquests.get() 命令中设置 verify=True)

Here is the documentation :