Urllib3是一個功能強大,條理清晰,用于HTTP客戶端的Python庫。許多Python的原生系統(tǒng)已經(jīng)開始使用urllib3。Urllib3提供了很多python標準庫urllib里所沒有的重要特性:
一、get請求
urllib3主要使用連接池進行網(wǎng)絡(luò)請求的訪問,所以訪問之前我們需要創(chuàng)建一個連接池對象,如下所示:
import urllib3url = "http://httpbin.org"http = urllib3.PoolManager();r = http.request('GET',url+"/get")print(r.data.decode())print(r.status)帶參數(shù)的getr = http.request('get','http://www.baidu.com/s',fields={'wd':'周杰倫'})print(r.data.decode())
經(jīng)查看源碼:
def request(self, method, url, fields=None, headers=None, **urlopen_kw):第一個參數(shù)method 必選,指定是什么請求,'get'、'GET'、'POST'、'post'、'PUT'、'DELETE'等,不區(qū)分大小寫。 第二個參數(shù)url,必選 第三個參數(shù)fields,請求的參數(shù),可選 第四個參數(shù)headers 可選
request請求的返回值是<urllib3.response.HTTPResponse object at 0x000001B3879440B8>
我們可以通過dir()查看其所有的屬性和方法。
dir(r)
直截取了一部分
#'data', 'decode_content', 'enforce_content_length', 'fileno', 'flush', 'from_httplib',# 'get_redirect_location', 'getheader', 'getheaders', 'headers', 'info', 'isatty',# 'length_remaining', 'read', 'read_chunked', 'readable', 'readinto', 'readline',# 'readlines', 'reason', 'release_conn', 'retries', 'seek', 'seekable', 'status',# 'stream', 'strict', 'supports_chunked_reads', 'tell', 'truncate', 'version', 'writable',# 'writelines']
二、post請求
import urllib3url = "http://httpbin.org"fields = { 'name':'xfy'}http = urllib3.PoolManager()r = http.request('post',url+"/post",fields=fields)print(r.data.decode())
可以看到很簡單,只是第一個參數(shù)get換成了post。
并且參數(shù)不需要再像urllib一樣轉(zhuǎn)換成byte型了。
三、設(shè)置headers
import urllib3headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}http = urllib3.PoolManager();r = http.request('get',url+"/get",headers = headers)print(r.data.decode())
四、設(shè)置代理
import urllib3url = "http://httpbin.org"headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}proxy = urllib3.ProxyManager('http://101.236.19.165:8866',headers = headers)r = proxy.request('get',url+"/ip")print(r.data.decode())
五、當(dāng)請求的參數(shù)為json
新聞熱點
疑難解答