Python has built-in libraries that encapsulate many common network protocols, so Python is a powerful network programming tool, a simple description of Python's network aspect programming.
urllib and URLLIB2 modules
Urllib and URLLIB2 are the strongest network working libraries in the Python standard library. Here is a brief introduction to the next Urllib module. The main use of the Urllib module in the common several modules:
Urlopenparseurlencodequoteunquote_safe_quotersunquote_plus
GET Request:
Use Urllib to make a GET request for the HTTP protocol and get the return value of the interface:
from urllib.request import Urlopen
URL = " http://127.0.0.1:5000/login?username=admin&password=123456 " Span style= "COLOR: #008000" ># open URL # urllib.request.urlopen (URL) # Span style= "COLOR: #008000" > Open the URL and read the data, return the result is bytes type: b ' {\ n "code": $, \ n "msg": "\xe6\x88\x90\xe5\x8a\x9f\xef\xbc\ x81 "\n}\n ' res = Urlopen (URL). Read () print # convert bytes type to string print (Res.decode ())
POST request:
fromUrllib.requestImportUrlopen fromUrllib.parseImportUrlEncode
URL='Http://127.0.0.1:5000/register'#request parameters, written as JSON type, followed by automatic conversion to key-value formdata = { "username":"55555", "pwd":"123456", "confirmpwd":"123456"}#use UrlEncode () to stitch the Key-value in the request parameter (dictionary)#stitching into username=hahaha&pwd=123456&confirmpwd=123456#use Encode () to convert a string to bytesparam =urlencode (data). Encode ()#output Result: B ' pwd=123456&username=hahaha&confirmpwd=123456 'Print(param)#POST request, incoming request parameters requiredres =urlopen (URL, param). Read () Res_str=Res.decode ()Print(Type (RES_STR), RES_STR)
Note: When using Urllib to request the Post interface, the above example, the request parameter type of the Post interface is Key-value form, does not apply the JSON form into the parameter.
Quote Module
Escape processing when there are special characters in the URL of the request.
from Import UrlEncode, quote, _safe_quoters, unquote, Unquote_plus
"#URL contains special characters, escape special characters, output: Https%3a//www.baidu.com/%3ftn%3d57095150_2_oem _dg%3a. %2c%5c%20new_url = quote (URL3)print(new_url)
Unquote module
Resolves an escaped special character.
fromUrllib.parseImportUrlEncode, quote, _safe_quoters, unquote, Unquote_plus
Url4='https%3a//www.baidu.com/%3ftn%3d57095150_2_oem_dg%3a..%2c%5c%20'#Resolves the escaped special character to a special characterNew_url =unquote (URL4)#output Result: https://www.baidu.com/?tn=57095150_2_oem_dg:..,\Print(New_url)#maximum degree of resolutionPrint('Plus:', Unquote_plus (URL4))
The above is a brief introduction of the next Urllib, on the interface processing also please refer to requests module ~ ~ ~
Python Note 8: Network programming