python中urlencode()的用法
在web后端开发,需要对于url进行反向生成,经常会用到这个urlencode()。那么到底这个是啥子呢?
- 传入参数类型:字典
- 功能:将存入的字典参数编码为URL查询字符串,即转换成以key1=value1&key2=value2的形式
1.url标准符号,数字字母
1. from urllib.parse import urlencode 2. base_url = "https://m.weibo.cn/api/container/getIndex?" 3. params1 = {"value": "english", "page": 1} 4. url1 = base_url + urlencode(params1) 5. print(urlencode(params1)) # value=english&page=1 6. print(url1) 7. # https://m.weibo.cn/api/container/getIndex?value=english&page=1
2.汉字,/,&,=,URL编码转化为%xx的形式
from urllib.parse import urlencode params2 = { 'name': "王二", 'extra': "/", 'special': '&', 'equal': '='} base_url = "https://m.weibo.cn/api/container/getIndex?" url2 = base_url + urlencode(params2) print(urlencode(params2)) print(url2) # 运行结果 # name=%E7%8E%8B%E4%BA%8C&extra=%2F&special=%26&equal=%3D # https://m.weibo.cn/api/container/getIndex?name=name=%E7%8E%8B%E4%BA%8C&extra=%2F&special=%26&equal=%3D
以上转载自:https://blog.csdn.net/gqv2009/article/details/125195931