收到粉絲私信說urllib庫的教程還沒寫,好吧,urllib是python自帶的庫,沒requests用着方便。原本嘛,python之禪(import this本身看)就說過,精簡,效率,方便也是你們的追求。不過你們有要求,那就寫一篇關於urllib的基礎教程。python
本文中的知識點:api
urllib是python自帶的,不用安裝,直接import進來便可post
注意這裏須要先定義opener,在打開咱們要發送的request請求。返回的字符串編碼用utf-8處理學習
import urllib.request from urllib.parse import urlencode opener = urllib.request.build_opener() # 發送request請求 req = urllib.request.Request('https://www.baidu.com/') res = opener.open(req) # 打印response code print(res.status) # urllib字符串默認是bytes類型,須要轉換到utf-8 print(res.read().decode('utf-8'))
運行下,結果以下圖 ui
注意仍是要模擬用戶請求,加上header參數this
import urllib.request from urllib.parse import urlencode headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'} # 代理IP,由快代理提供 proxy = '124.94.203.122:20993' proxy_values = "%(ip)s" % {'ip': proxy} proxies = {"http": proxy_values, "https": proxy_values} # 設置代理 handler = urllib.request.ProxyHandler(proxies) opener = urllib.request.build_opener(handler) # 發送request請求 req = urllib.request.Request('https://www.baidu.com/s?ie=UTF-8&wd=ip', headers=headers) res = opener.open(req) # 打印response code print(res.status) # urllib字符串默認是bytes類型,須要轉換到utf-8 print(res.read().decode('utf-8'))
運行下,結果以下。正常打開了這個網頁 ***編碼
上述的默認使用的是get請求,那要使用post加一個method參數便可。 注意method參數POST是大寫,由於個人urllib源碼提示得大寫。不過有的同窗小寫也能夠,你們能夠本身試下。url
import urllib.request from urllib.parse import urlencode page_url = 'https://dev.kdlapi.com/testproxy/' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'} # 代理IP,由快代理提供 proxy = '115.203.13.59:21216' proxy_values = "%(ip)s" % {'ip': proxy} proxies = {"http": proxy_values, "https": proxy_values} # 設置代理 handler = urllib.request.ProxyHandler(proxies) opener = urllib.request.build_opener(handler) # 發送request post請求 data = bytes(urlencode({"info": "send post request"}), encoding="utf-8") req = urllib.request.Request(url=page_url, headers=headers, data=data, method="POST") res = opener.open(req) # 打印response code print(res.status) # urllib字符串默認是bytes類型,須要轉換到utf-8 print(res.read().decode('utf-8'))
運行下試試,post成功,如圖 進階學習:spa