按照标准, URL 只允许一部分 ASCII 字符(数字字母和部分符号),其他的字符(如汉字)是不符合 URL 标准的。所以 URL 中使用其他字符就需要进行 URL 编码。
在代码中导入:
from urllib import parse
将中文进行urlencode编码使用函数
urllib.parse.quote(string, safe='/', encoding=None, errors=None)
而将编码后的字符串转为中文,则使用
urllib.parse.unquote(string, encoding='utf-8', errors='replace')
但是parse.quote方法不会对-._/09AZaz进行编码,参数safe是指定某字符不被urlencode,默认为'/',使用quote 包含编码斜线可使用safe=‘’
使用parse.quote_plus('a&b/c') 方法可以进行/的编码
parse.unquote('9+2') #不解码加号
parse.unquote_plus('9+2') #把加号解码为空格