Python使用quote、unquote、urlencode、urldecode对url编码解码

简介: Python使用quote、unquote、urlencode、urldecode对url编码解码

1、对单个字符串编码


from urllib.parse import quote, unquote
# 编码
print(quote("美国"))
# %E7%BE%8E%E5%9B%BD
# 解码
print(unquote("%E7%BE%8E%E5%9B%BD"))
# 美国

2、对key-value字典数据编码


from urllib.parse import unquote, urlencode
data = {
    "name": "Tom",
    "country": "美国",
    "age": 23
}
# 编码
print(urlencode(data))
# name=Tom&country=%E7%BE%8E%E5%9B%BD&age=23
# 解码
print(unquote("name=Tom&country=%E7%BE%8E%E5%9B%BD&age=23"))
# name=Tom&country=美国&age=23

3、自定义实现url解码

tip: urllib库没有提供 urldecode 函数


# 将查询字符串转为dict字典数据类型
def urldecode(query):
    item = {}
    for key_value in unquote(query).split("&"):
        key, value = key_value.split("=")
        item[key] = value
    return item
print(urldecode("name=Tom&country=%E7%BE%8E%E5%9B%BD&age=23"))
# {'name': 'Tom', 'country': '美国', 'age': '23'}
相关文章
|
9月前
|
数据采集 存储 NoSQL
分布式爬虫去重:Python + Redis实现高效URL去重
分布式爬虫去重:Python + Redis实现高效URL去重
|
11月前
|
数据采集 监控 Python
Python爬虫异常处理:自动跳过无效URL
Python爬虫异常处理:自动跳过无效URL
Python爬虫异常处理:自动跳过无效URL
|
安全 Java 程序员
【HTTP】认识 URL 和 URL encode
【HTTP】认识 URL 和 URL encode
285 0
|
数据采集 索引 Python
Python中这样操作url也太爽了吧
Python中这样操作url也太爽了吧
346 5
|
算法 Python
【Leetcode刷题Python】百分号解码
深信服公司的算法笔试题.
228 1
|
前端开发 安全 测试技术
【Python】已解决:The method is not allowed for the requested URL.
【Python】已解决:The method is not allowed for the requested URL.
2070 3
【Azure API 管理】Azure API Management在设置 Policy时,如何对URL进行解码呢? 使用 HttpUtility.UrlDecode 出错
【Azure API 管理】Azure API Management在设置 Policy时,如何对URL进行解码呢? 使用 HttpUtility.UrlDecode 出错
152 0
|
Python
python编码和解码
【5月更文挑战第8天】
194 4
|
Python
Python字符串和字节使用正确的编码/解码
【5月更文挑战第6天】Python字符串和字节使用正确的编码/解码
229 2
|
存储 SQL Python
`urllib.parse`模块是Python标准库`urllib`中的一个子模块,它提供了处理URL(统一资源定位符)的实用功能。这些功能包括解析URL、组合URL、转义URL中的特殊字符等。
`urllib.parse`模块是Python标准库`urllib`中的一个子模块,它提供了处理URL(统一资源定位符)的实用功能。这些功能包括解析URL、组合URL、转义URL中的特殊字符等。

热门文章

最新文章

推荐镜像

更多