urllib库(三)parse模块:quote()/quote_plus(),unquote()/unquote_plus(),quote_from_bytes()

urllib.parse模块在功能上分为两大类:URL parsing(URL解析)和URL quoting(URL引用)
上一节已经介绍了url解析 本节介绍url引用
URL解析传送门(https://blog.csdn.net/Wjf7496/article/details/109787586)

(1)quote()/quote_plus()

上一节介绍的urllib.parse.urlencode()函数是对一个字典或者sequence of 'two-tuple'
进行编码
若只是对单个str或者bytes编码则需要使用quote()/quote_plus()

函数定义
urllib.parse.quote(string,safe='/',encoding=None,errors=None)
	string:
		strbytes型数据
		其中下划线,句号,逗号,斜线和字母数字这类符号不需要转化,其它的则需要转化。
		另外URL不能使用的字符(如中文)前会被加上百分号(%)同时转换成十六进制,即<%xx>的形式
	safe:
		safe字符串包含一些不能转换的字符,默认是斜线(/)。
	encoding、errors:
		这两个参数指定如何处理str.encode()方法接受的非ascii字符
	
二者的区别在于对特殊字符编码的方式不一样 如
	quote()      不编码斜线;        空格‘ ’编码为‘%20’
	quote_plus() 会编码斜线为‘%2F; 空格‘ ’编码为‘+’
	等等


>>> from urllib import parse
>>> parse.quote('a&b/c')  
'a%26b/c'
>>> parse.quote_plus('a&b/c')  
'a%26b%2Fc'

>>> parse.quote('a&b c')
'a%26b%20c'
>>> parse.quote_plus('a&b c')
'a%26b+c'

编码后的url传递后接受完毕就要解码,urllib提供了unquote(),urluquote_plus()两个函数实现url解码,没有urldecode()!

(2)unquote()/unquote_plus()

unquote()
	unquote(string, encoding='utf-8', errors='replace')
	不解码加号,默认string的编码utf-8
unquote_plus() 
	unquote_plus(string, encoding='utf-8', errors='replace')
	加号解码为空格 默认string的编码utf-8
	
二者的返回值类型都是str	
注意这里的encoding指定的是string参数的编码格式,不是终端编码格式

from urllib import parse
print(parse.unquote('1+2'))# '1+2'
print(parse.unquote_plus('1+2'))# '1 2'

终端utf-8:
>>> parse.quote('魔兽')
'%E9%AD%94%E5%85%BD'
>>> parse.unquote('%E9%AD%94%E5%85%BD')
'魔兽'
>>> parse.unquote(parse.quote('魔兽'))
'魔兽'

urlencode时quote()就是把字符串'魔兽'转车utf-8编码'\xe9\xad\x94\xe5\x85\xbd'
然后把\x替换成%得到'%E9%AD%94%E5%85%BD'
urldecode时unquote()这个函数的输出是对应中文'魔兽'在utf-8下的编码'\xe9\xad\x94\xe5\x85\xbd'得到中文'魔兽'

那么如果终端是gbk编码的,解码utf-8的字符串需要指定encoding='utf-8'输出,否则就乱码 
同样在终端utf-8下解码gbk的字符串也会乱码,需要指定参数encoding='gbk'
因为quote()unquote()默认编码都是utf-8

终端utf-8编码:
'魔兽'的gbk编码是'\xc4\xa7\xca\xde'

>>> parse.unquote('%C4%A7%CA%DE')
'ħ��'
>>> parse.unquote('%C4%A7%CA%DE',encoding='gbk')
'魔兽'

(3)quote_from_bytes()/unquote_from_bytes()

(1)quote_from_bytes()
	类似于quote(),
	不过它只接受bytes,并且不执行string到bytes的编码
	str 需要先转成bytes 两种办法:
		str.encode(encoding)bytes(str,encoding)

quote(string,safe,encoding,errors) 与 
quote_from_bytes(str.encode(encoding),safe)等价。`

(2)unquote_to_bytes(string)
	类似于unquote(),不过它接受一个str或者bytes,返回一个bytes object

parse模块包含的常用方法总结(https://blog.csdn.net/qq_36759224/article/details/99711754)

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值