- urlencode()
- 传入参数类型:字典
- 功能:将存入的字典参数编码为URL查询字符串,即转换成以key1=value1&key2=value2的形式
- 导入:from urllib.parse import urlencode
- Ps:url单个字符串编码用quote()函数
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