编程语言
首页 > 编程语言> > Python之urlencode()使用方法

Python之urlencode()使用方法

作者:互联网

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

3.以上两例子默认utf8编码,如果用gb2312编码,则需指定

from urllib.parse import urlencode
params2 = {
    'name': "王二",
    'extra': "/",
    'special': '&',
    'equal': '='}
base_url = "https://m.weibo.cn/api/container/getIndex?"
url2 = base_url + urlencode(params2, encoding='gb2312')
print(urlencode(params2, encoding='gb2312'))
print(url2)
# 运行结果
# name=%CD%F5%B6%FE&extra=%2F&special=%26&equal=%3D
# https://m.weibo.cn/api/container/getIndex?name=%CD%F5%B6%FE&extra=%2F&special=%26&equal=%3D

标签:urlencode,name,extra,Python,url,方法,special,cn
来源: https://www.cnblogs.com/gqv2009/p/urlencode.html