url的param与dict转换
urllib.parse.urlencode
urlencode
from urllib import parse from urllib.request import urlopen from urllib import request values = {'username': 'xxxxxxxxx@qq.com', 'password': 'XXXX'} data = parse.urlencode(values) # 提交类型不能为str,需要为byte类型 print(data,type(data)) # 'username=xxxxxxxxx%40qq.com&password=XXXX' <class 'str'> url = 'https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn' request = request.Request(url, data.encode("utf-8")) # 提交类型不能为str,需要为byte类型 response = urlopen(request) print(response.read().decode())
from urllib.parse import unquote
from urllib.parse import unquote from urllib.parse import urlencode d = {"a":1,"b":[2,"bbb","中国"],"c":"和平"} d_urlencode = urlencode(d) d1_urlencode = urlencode(d,encoding="gbk") print(d_urlencode) # a=1&b=%5B2%2C+%27bbb%27%2C+%27%E4%B8%AD%E5%9B%BD%27%5D&c=%E5%92%8C%E5%B9%B3 print(d1_urlencode) # a=1&b=%5B2%2C+%27bbb%27%2C+%27%D6%D0%B9%FA%27%5D&c=%BA%CD%C6%BD # 解码 d_unquote = unquote(d_urlencode) d1_unquote = unquote(d1_urlencode) print(d_unquote) # a=1&b=[2,+'bbb',+'中国']&c=和平 print(d1_unquote) # a=1&b=[2,+'bbb',+'�й�']&c=��ƽ d2_unquote = unquote(d1_urlencode,encoding="gbk") # 默认解码是utf-8 print(d2_unquote) # a=1&b=[2,+'bbb',+'中国']&c=和平
url转换为dict
from urllib import parse url = "https://search.jd.com/search?coupon_batch=112280806&coupon_id=46034227333&qrst=1&rt=1&stop=1&vt=2&scc=1&psort=1&wtype=1&ev=exbrand_%E9%AD%85%E6%97%8F%EF%BC%88MEIZU%EF%BC%89%5Eexprice_0-1000%5E&uc=0&stock=0#J_searchWrap" res = dict(parse.parse_qsl(url)) print(res) # {'https://search.jd.com/search?coupon_batch': '112280806', 'coupon_id': '46034227333', 'qrst': '1', 'rt': '1', 'stop': '1', 'vt': '2', 'scc': '1', 'psort': '1', 'wtype': '1', 'ev': 'exbrand_魅族(MEIZU)^exprice_0-1000^', 'uc': '0', 'stock': '0#J_searchWrap'} res = dict(parse.parse_qsl(url.partition("?")[2])) print(res) # {'coupon_batch': '112280806', 'coupon_id': '46034227333', 'qrst': '1', 'rt': '1', 'stop': '1', 'vt': '2', 'scc': '1', 'psort': '1', 'wtype': '1', 'ev': 'exbrand_魅族(MEIZU)^exprice_0-1000^', 'uc': '0', 'stock': '0#J_searchWrap'} url='_from=R40&LH_BIN=1&_sop=13&LH_Complete=1&LH_Sold=1&_udlo=24&_udhi=48&_ipg=200&_pgn=1&_skc=0' res = dict(parse.parse_qsl(url)) print(res) # {'_from': 'R40', 'LH_BIN': '1', '_sop': '13', 'LH_Complete': '1', 'LH_Sold': '1', '_udlo': '24', '_udhi': '48', '_ipg': '200', '_pgn': '1', '_skc': '0'}
django.http.request.QueryDict
django的request.GET类型实际是QueryDict,不过是不可变的mutable=False。
if __name__ == "__main__": import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "first_review.settings") from django.http.request import QueryDict qd3 = QueryDict("a=1&b=2",mutable=True) qd3.update({"c":3}) qd3.setdefault("d","ddd") qd3.setlistdefault("e",[555,"eee"]) print(qd3) # <QueryDict: {'a': ['1'], 'b': ['2'], 'c': [3], 'd': ['ddd'], 'e': [555, 'eee']}> print(qd3.urlencode()) # a=1&b=2&c=3&d=ddd&e=555&e=eee django的QueryDict.urlencode()