python 下載圖片的集中方法
阿新 • • 發佈:2018-12-05
總結下:
url = 'http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_1501509923353_mthumb.jpg'
1、urllib庫——urlretrieve
import urllib def report_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
import urllib r = urllib.urlopen(url) data = r.read() with open("1234.jpg",'wb') as f: f.write(data)
3、requests
#coding:utf-8 import requests r= requests.get(url) with open("123.jpg",'wb') as f: f.write(r.content)
注意:
resp.text返回的是Unicode型的資料。
resp.content返回的是bytes型也就是二進位制的資料。
urlencode的傳送請求同時傳data表單
import urllib import urllib2 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() #讀取反饋的內容