下载网址有密码 怎么用python下载
时间: 2024-01-09 16:15:57 浏览: 23
你可以使用 Python 的 requests 库和 urllib 库来下载带密码的文件。以下是一个示例代码,可以下载一个需要密码的文件:
```python
import requests
import urllib.request
import urllib.parse
import urllib.error
url = 'https://example.com/download.zip'
username = 'myusername'
password = 'mypassword'
# Create an opener with authentication credentials
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, username, password)
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(handler)
# Install the opener
urllib.request.install_opener(opener)
# Download the file
response = urllib.request.urlopen(url)
data = response.read()
# Save the file to disk
with open('download.zip', 'wb') as f:
f.write(data)
```
在上面的代码中,我们首先创建了一个带有身份验证凭据的 opener,然后使用 urllib 库的 urlopen() 函数打开 URL,并将响应读入内存。最后,我们将文件保存到磁盘上。
请注意,这种方法只适用于 HTTP 基本身份验证,对于其他类型的身份验证(如 OAuth 或 OpenID Connect),您需要使用相应的库来处理身份验证流程。