urlencode()

urlencode()是urllib库中parse模块的方法,需要导入才能使用。 

导入方式: from urllib.parse import urlencode

该方法能将Python字典类型的数据转为url参数字符串。

示例:

from urllib.parse import urlencode

dict1 = {
    "name": "张三",
    "age": 22,
    "score": 87.5,
    "skill": "eat"
}

params = urlencode(dict1)
print(params)   # name=%E5%BC%A0%E4%B8%89&age=22&score=87.5&skill=eat

除了传入字典,还能传入编码类型,默认是utf-8(encoding='utf-8').

from urllib.parse import urlencode

dict1 = {
    "name": "张三",
    "age": 22,
    "score": 87.5,
    "skill": "eat"
}

params = urlencode(dict1, encoding='gbk')
print(params)   # name=%D5%C5%C8%FD&age=22&score=87.5&skill=eat

 

posted on 2023-04-12 12:11  木去  阅读(268)  评论(0)    收藏  举报