Python Note 8: network programming, python note Network Programming
Python has a built-in library that encapsulates many common network protocols. Therefore, python has become a powerful network programming tool. Here is a simple description of python network 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 urllib module. The following modules are commonly used in the urllib module:
urlopenparseurlencodequoteunquote_safe_quotersunquote_plus
GET request:
Use urllib for http get requests and obtain the return values of the interfaces:
From urllib. request import urlopen
Url = 'HTTP: // 127.0.0.1: 5000/login? Username = admin & password = 123456 '# Open url # urllib. request. urlopen (url) # Open the url and read data. The returned result is bytes type: 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) # convert bytes type to print (res. decode ())
POST request:
From urllib. request import urlopenfrom urllib. parse import urlencode
Url = 'HTTP: // 127.0.0.1: 5000/register '# request parameter, which is written as the json type and is automatically converted to the key-value format data = {"username ": "55555", "pwd": "123456", "confirmpwd": "123456"} # Use urlencode () to set request parameters (dictionary) key-value in # splice to username = hahaha & pwd = 123456 & confirmpwd = 123456 # Use encode () to convert the string to bytesparam = urlencode (data ). encode () # output result: B 'pwd = 123456 & username = hahaha & confirmpwd = 123456 'print (param) # For post requests, the request parameter res = urlopen (url, param ). read () res_str = res. decode () print (type (res_str), res_str)
Note: When urllib is used to request the post interface, in the preceding example, the request parameter type of the post interface is in the key-value format and does not apply to json input parameters.
Quote Module
Escape the request url with special characters.
From urllib. parse import urlencode, quote, _ safe_quoters, unquote, unquote_plus
Url3 = 'https: // www.baidu.com /? Tn = 57095150_2_oem_dg :.., \ '# When the url contains special characters, escape the special characters and output: https % 3A // Signature = quote (url3) print (new_url)
Unquote Module
Parses escaped special characters.
From urllib. parse import urlencode, quote, _ safe_quoters, unquote, unquote_plus
Url4 = 'https % 3A // tags = unquote (url4) # output result: https://www.baidu.com /? Tn = 57095150_2_oem_dg:..., \ print (new_url) # maximum resolution print ('plus: ', unquote_plus (url4 ))
The above is a brief introduction to urllib. For interface processing, please refer to the requests module ~~~