总结下:
url = 'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_1501509923353_mthumb.jpg'
1、urllib库——urlretrieve
importurllibdefreport_hook(count, block_size, total_size):print '%02d%%'%(100.0 * count * block_size/total_size)
urllib.urlretrieve("http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_1501509923353_mthumb.jpg",r'D:\DESKTOP\1.jpg',reporthook= report_hook)
顺便提一下,report_hook是回调函数——reporthook:是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函数来显示当前的下载进度。
2、还是urllib——urlopen
importurllib
r=urllib.urlopen(url)
data=r.read()
with open("1234.jpg",'wb') as f:
f.write(data)
3、requests
#coding:utf-8
importrequests
r=requests.get(url)
with open("123.jpg",'wb') as f:
f.write(r.content)
注意:
resp.text返回的是Unicode型的数据。
resp.content返回的是bytes型也就是二进制的数据。
urlencode的发送请求同时传data表单
importurllibimporturllib2
url= 'http://www.someserver.com/register.cgi'values= {'name' : 'WHY','location' : 'SDU','language' : 'Python'}
data= urllib.urlencode(values) #编码工作
req = urllib2.Request(url, data) #发送请求同时传data表单
response = urllib2.urlopen(req) #接受反馈的信息
the_page = response.read() #读取反馈的内容