標籤:register 常見 username style encode 網路編程 urlopen tps family
python內建封裝了很多常見的網路通訊協定的庫,因此python成為了一個強大的網路編程工具,這裡是對python的網路方面編程的一個簡單描述。
urllib 和 urllib2模組
urllib 和urllib2是python標準庫中最強的網路工作庫。這裡簡單介紹下urllib模組。本次主要用urllib模組中的常用的幾個模組:
urlopenparseurlencodequoteunquote_safe_quotersunquote_plus
GET請求:
使用urllib 進行http協議的get請求,並擷取介面的傳回值:
from urllib.request import urlopen
url = ‘http://127.0.0.1:5000/login?username=admin&password=123456‘#開啟url#urllib.request.urlopen(url)#開啟url並讀取資料,返回結果是bytes類型:b‘{\n "code": 200, \n "msg": "\xe6\x88\x90\xe5\x8a\x9f\xef\xbc\x81"\n}\n‘res = urlopen(url).read()print(type(res), res)#將bytes類型轉換為字串print(res.decode())
POST請求:
from urllib.request import urlopenfrom urllib.parse import urlencode
url = ‘http://127.0.0.1:5000/register‘#請求參數,寫成json類型,後面是自動轉換為key-value形式data = { "username": "55555", "pwd": "123456", "confirmpwd": "123456"}#使用urlencode(),將請求參數(字典)裡的key-value進行拼接#拼接成username=hahaha&pwd=123456&confirmpwd=123456#使用encode()將字串轉換為bytesparam = urlencode(data).encode()#輸出結果:b‘pwd=123456&username=hahaha&confirmpwd=123456‘print(param)#post請求,需要傳入請求參數res = urlopen(url, param).read()res_str = res.decode()print(type(res_str), res_str)
註:使用urllib請求post介面時,以上例子,post介面的請求參數類型是key-value形式,不適用json形式入參。
Quote模組
對請求的url中帶有特殊字元時,進行轉義處理。
from urllib.parse import urlencode, quote, _safe_quoters, unquote, unquote_plus
url3 = ‘https://www.baidu.com/?tn=57095150_2_oem_dg:..,\\ ‘#url中包含特殊字元時,將特殊字元進行轉義, 輸出:https%3A//www.baidu.com/%3Ftn%3D57095150_2_oem_dg%3A..%2C%5C%20new_url = quote(url3)print(new_url)
Unquote模組
對轉義過的特殊字元進行解析操作。
from urllib.parse import urlencode, quote, _safe_quoters, unquote, unquote_plus
url4 = ‘https%3A//www.baidu.com/%3Ftn%3D57095150_2_oem_dg%3A..%2C%5C%20‘#將轉義後的特殊字元進行解析,解析為特殊字元new_url = unquote(url4)#輸出結果:https://www.baidu.com/?tn=57095150_2_oem_dg:..,\print(new_url)#最大程度的解析print(‘plus:‘, unquote_plus(url4))
以上就是簡單介紹下urllib,對介面處理時還請參考requests模組~~~
Python筆記8:網路編程