4 python
我的名为“blueberry.jpg”的文件开始下载,当我手动单击以下网址时,前提是在询问时输入用户名和密码:http : //example.com/blueberry/download
我怎样才能使用 Python 做到这一点?
import urllib.request
url = 'http://example.com/blueberry/download'
data = urllib.request.urlopen(url).read()
fo = open('E:\\quail\\' + url.split('/')[1] + '.jpg', 'w')
print (data, file = fo)
fo.close()
Run Code Online (Sandbox Code Playgroud)
但是上面的程序没有写入所需的文件,我如何提供所需的用户名和密码?
Use requests,它为 Python 中的各种 url 库提供了一个更友好的界面:
import os
import requests
from urlparse import urlparse
username = 'foo'
password = 'sekret'
url = 'http://example.com/blueberry/download/somefile.jpg'
filename = os.path.basename(urlparse(url).path)
r = requests.get(url, auth=(username,password))
if r.status_code == 200:
with open(filename, 'wb') as out:
for bits in r.iter_content():
out.write(bits)
Run Code Online (Sandbox Code Playgroud)
更新:对于 Python3,使用以下命令获取 urlparse: from urllib.parse import urlparse
| 归档时间: |
|
| 查看次数: |
15963 次 |
| 最近记录: |