python3文件下载
方法一:
import urllib.request url = 'https://www.baidu.com/demo.rar' urllib.request.urlretrieve(url, 'D:/demo.rar')
#Python3.3后urllib2已经不能再用,只能用urllib.request来代替
使用 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。
|
1
|
urlretrieve(url, [filename=None, [reporthook=None, [data=None]] |
说明:
-
参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
-
参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
-
参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
实例:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/usr/bin/python#encoding:utf-8import urllib.requestimport osdef Schedule(a,b,c): ''''' a:已经下载的数据块 b:数据块的大小 c:远程文件的大小 ''' per = 100.0 * a * b / c if per > 100 : per = 100 print '%.2f%%' % perurl = 'http://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.bz2'#local = url.split('/')[-1]local = os.path.join('/data/software','Python-3.6.5.tar.bz2')urllib.request.urlretrieve(url,local,Schedule)######output#######0.00%#0.07%#0.13%#0.20%#....#99.94%#100.00% |
方法二:
使用urllib的urlopen()函数
实例:
url = 'https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/'\
'sign=89d2ca65a2014c08196e20a33a4b2e30/38dbb6fd5266d01669d2d9e49c2bd40734fa3536.jpg'
f = urllib.request.urlopen(url)
data = f.read()
with open("demo.jpg", "wb") as code:
code.write(data)
方法三:
使用requests模块
实例:
import requests
url = 'http://ww.pythontab.com/test/demo.zip'
r = requests.get(url)
with open("demo3.zip", "wb") as code:
code.write(r.content)
浙公网安备 33010602011771号