python爬蟲之urllib3的使用示例
Urllib3是一個功能強大,條理清晰,用于HTTP客戶端的Python庫。許多Python的原生系統(tǒng)已經開始使用urllib3。Urllib3提供了很多python標準庫urllib里所沒有的重要特性:
- 線程安全
- 連接池
- 客戶端SSL/TLS驗證
- 文件分部編碼上傳
- 協(xié)助處理重復請求和HTTP重定位
- 支持壓縮編碼
- 支持HTTP和SOCKS代理
一、get請求
urllib3主要使用連接池進行網絡請求的訪問,所以訪問之前我們需要創(chuàng)建一個連接池對象,如下所示:
import urllib3 url = "http://httpbin.org" http = urllib3.PoolManager(); r = http.request('GET',url+"/get") print(r.data.decode()) print(r.status) 帶參數(shù)的get r = http.request('get','http://www.baidu.com/s',fields={'wd':'周杰倫'}) print(r.data.decode())
經查看源碼:
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 urllib3 url = "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一樣轉換成byte型了。
三、設置headers
import urllib3 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' } http = urllib3.PoolManager(); r = http.request('get',url+"/get",headers = headers) print(r.data.decode())
四、設置代理
import urllib3 url = "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())
五、當請求的參數(shù)為json
在發(fā)起請求時,可以通過定義body 參數(shù)并定義headers的Content-Type參數(shù)來發(fā)送一個已經過編譯的JSON數(shù)據(jù)
import urllib3 url = "http://httpbin.org" import json data = {'name':'徐繁韻'} json_data = json.dumps(data) http = urllib3.PoolManager() r = http.request('post',url+"/post",body = json_data,headers = {'Content-Type':'application/json'}) print(r.data.decode('unicode_escape'))
六、上傳文件
#元組形式 with open('a.html','rb') as f: data = f.read() http = urllib3.PoolManager() r = http.request('post','http://httpbin.org/post',fields = {'filefield':('a.html',data,'text/plain')}) print(r.data.decode()) #二進制形式 r = http.request('post','http://httpbin.org/post',body = data,headers={'Content-Type':'image/jpeg'}) print(r.data.decode())
七、超時設置
# 1全局設置超時 # http = urllib3.PoolManager(timeout = 3) # 2在request里設置 # http.request('post','http://httpbin.org/post',timeout = 3)
八、重試和重定向
import urllib3 http = urllib3.PoolManager() #重試 r = http.request('post','http://httpbin.org/post',retries = 5) #請求重試測次數(shù)為5次 ,默認為3ci print(r.retries) #Retry(total=5, connect=None, read=None, redirect=0, status=None) #關閉重試 http.request('post','http://httpbin.org/post',retries = False) #請求重試測次數(shù)為5次 ,默認為3ci r = http.request('get','http://httpbin.org/redirect/1',redirect = False) print(r.retries)# Retry(total=3, connect=None, read=None, redirect=None, status=None) print(r.status) print(r.data.decode()) print("--------------------") print(r.get_redirect_location()) #302不是異常
九、urllib3 本身設置了https的處理,但是有警告
雖然可以請求,但是報如下警告:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
禁用警告:
import urllib3 urllib3.disable_warnings() #禁用各種警告 url = "https://www.12306.cn/mormhweb/" http = urllib3.PoolManager() r = http.request('get',url) print(r.data.decode())
urllib3很強大,但是并沒有requests好用。了解為主。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解如何在PyQt5中實現(xiàn)平滑滾動的QScrollArea
Qt 自帶的 QScrollArea 滾動時只能在兩個像素節(jié)點之間跳變,看起來很突兀。所以本文將通過定時器,重寫 wheelEvent() 來實現(xiàn)平滑滾動,需要的可以參考一下2023-01-01Jmeter如何使用BeanShell取樣器調用Python腳本
這篇文章主要介紹了Jmeter使用BeanShell取樣器調用Python腳本,文章圍繞Jmeter調用Python腳本的相關詳情展開標題內容,需要的小伙伴可以參考一下2022-03-03Numpy中np.random.rand()和np.random.randn() 用法和區(qū)別詳解
這篇文章主要介紹了Numpy中np.random.rand()和np.random.randn() 用法和區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10Python 剪繩子的多種思路實現(xiàn)(動態(tài)規(guī)劃和貪心)
這篇文章主要介紹了Python 剪繩子的多種思路實現(xiàn)(動態(tài)規(guī)劃和貪心),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02實現(xiàn)Windows下設置定時任務來運行python腳本
這篇文章主要介紹了實現(xiàn)Windows下設置定時任務來運行python腳本的完整過程,有需要的朋友可以借鑒參考下,希望對廣大讀者朋友能夠有所幫助2021-09-09