阿布云

你所需要的,不仅仅是一个好用的代理。

Python笔记:网络编程

阿布云 发表于

3.png

python内置封装了很多常见的网络协议的库,因此python成为了一个强大的网络编程工具,这里是对python的网络方面编程的一个简单描述。

urllib 和 urllib2模块

urllib 和urllib2是python标准库中最强的网络工作库。这里简单介绍下urllib模块。本次主要用urllib模块中的常用的几个模块:

urlopen

parse

urlencode

quote

unquote

_safe_quoters

unquote_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请求:

rom 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()将字符串转换为bytes

param = 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%20

new_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模块~~~