why decode || encode
URL参数字符串中使用key=value键值对这样的形式来传参,键值对之间以&符号分隔,如果value字符串中包含了=或者&,那么势必会造成接收Url的服务器解析错误,因此必须将引起歧义的&和=符号进行转义,也就是对其进行编码。
requests
在用Python+requests做接口自动化过程中,http协议在发送url的时候,是以urlencode的编码格式传过去的,通常requests库会自动处理。
@staticmethod
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, "read"):
return data
elif hasattr(data, "__iter__"):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(
k.encode("utf-8") if isinstance(k, str) else k,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
# 此处对params进行urlencode
return urlencode(result, doseq=True)
else:
return data
urllib.parse
urllib.parse 里面4个方法:urlencode、urldecode、quote 和 unquote, 分别参数编码与解码
urlencode
# Encode a dict or sequence of two-element tuples into a URL query string.
urlencode(query, doseq=False, safe='', encoding=None, errors=None,quote_via=quote_plus)
urlencode方法能对字典编码
from urllib.parse import urlencode
payload = {
"content": '<head title="test" name="xxx">',
}
print(urlencode(payload))
------------------------------------------
content=%3Chead+title%3D%22test%22+name%3D%22xxx%22%3E
quote
quote方法能对字符串编码
# quote('abc def') -> 'abc%20def'
quote(string, safe='/', encoding=None, errors=None)
from urllib.parse import quote
print(quote('https://www.xxx.com?content=<head title="test" name="xxx">+'))
-----------------------------------------------------
https%3A//www.xxx.com%3Fcontent%3D%3Chead%20title%3D%22test%22%20name%3D%22xxx%22%3E%2B
urlencode,unquote
略
requests转码的效果
import requests
from urllib3 import disable_warnings
url = 'https://www.xxx.com?content=<head title="test" name="xxx">+'
disable_warnings()
res = requests.get(url, timeout=0.1, verify=False)
print(res.url)
---------------------------------------------------
/?content=%3Chead%20title=%22test%22%20name=%22xxx%22%3E+