Python筆記8:網路編程,python筆記網路編程

來源:互聯網
上載者:User

Python筆記8:網路編程,python筆記網路編程

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模組~~~


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.