首页 技术 正文
技术 2022年11月6日
0 收藏 774 点赞 324 浏览 1766 个字

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

 

from urllib.request import urlopen
from 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模块~~~

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291