平时见到的url参数都是key-value, 一般vlaue都是字符串类型的

如果有幸和我一样遇到字典,列表等参数,那么就幸运了

python2代码

import json
from urllib import urlencode

# 1. 直接将url编码
params = {
  "name": "Tom",
  "hobby": ["ball", "swimming"],
  "books": [{"name": "语文", "pages": 20}]
}

print(urlencode(params))
"""
hobby=%5B%27ball%27%2C+%27swimming%27%5D&
books=%5B%7B%27name%27%3A+%27%5Cxe8%5Cxaf%5Cxad%5Cxe6%5Cx96%5Cx87%27%2C+%27pages%27%3A+20%7D%5D&
name=Tom
"""

# 2. 先用json序列化字典和列表参数
params = {
  "name": "Tom",
  "hobby": json.dumps(["ball", "swimming"]),
  "books": json.dumps([{"name": "语文", "pages": 20}])
}

print(urlencode(params))

"""
hobby=%5B%22ball%22%2C+%22swimming%22%5D&
books=%5B%7B%22name%22%3A+%22%5Cu8bed%5Cu6587%22%2C+%22pages%22%3A+20%7D%5D&
name=Tom
"""

观察1 和2 序列化出来的url参数不是一样的,如果第一种方式的url不能正常访问,那么就用第二种

标签:
Python,url,编码,转换

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com