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

标签 python python-3.x authentication https

基本上我需要一个给定 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 :

关于python - HTTP 错误 401 : Authorization Required while downloading a file from HTTPS website and saving it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20361249/

相关文章:

python - 使用递归从字符列表打印 n 长度组合

python - 防止 Celery Beat 运行相同的任务

python - 如何从 Python Pandas 系列或数据框中的行中删除省略号,当长行/宽列被截断时显示?

python - 无法将 'auto' 转换为 dtype float 的 EagerTensor

apache - svn 无密码身份验证 - 使用 SSL 信任

ubuntu - 在 Ubuntu 中登录时挂载 TrueCrypt 卷

python - 有没有办法获得框架 child 的引用?

python - 列出所有连续的子数组

python - 如何从 multipart/form-data 请求中提取二进制数据? (Python)(由 AWS API Gateway 编码的多部分请求 base64)

c++ - 套接字身份验证和加密