Notion Blog
技术分享1 分钟阅读

python URL编码解码

对URL进行编码和解码是非常常见的需求。

在Python中实现URL编码和解码的方法:

对URL进行编码(Percent encoding):

from urllib.parse import quote

url = 'https://www.example.com/path/to/file?a=1&b=2'
encoded_url = quote(url)
print(encoded_url)

# 输出:https%3A//www.example.com/path/to/file%3Fa%3D1%26b%3D2

quote()函数可以对URL进行编码。

对URL进行解码:

from urllib.parse import unquote

encoded_url = 'https%3A//www.example.com/path/to/file%3Fa%3D1%26b%3D2'
decoded_url = unquote(encoded_url)
print(decoded_url)

# 输出:https://www.example.com/path/to/file?a=1&b=2

unquote()函数可以对URL进行解码。

urllib.parse模块提供了对URL进行编解码所需的函数。quote()和unquote()是最常用的两种。

在JavaScript中

可以通过encodeURI()和decodeURI()来实现URL的编码和解码:

let url = 'https://www.example.com/path/to/file?a=1&b=2';

let encodedUrl = encodeURI(url);

console.log(encodedUrl);
// https%3A%2F%2Fwww.example.com%2Fpath%2Fto%2Ffile%3Fa%3D1%26b%3D2

decodeURI()可以把encodeURI()编码的URL解码:

let encodedUrl = 'https%3A%2F%2Fwww.example.com%2Fpath%2Fto%2Ffile%3Fa%3D1%26b%3D2';

let decodedUrl = decodeURI(encodedUrl);

console.log(decodedUrl);
// https://www.example.com/path/to/file?a=1&b=2

有关使用上的问题,欢迎您在底部评论区留言,一起交流~

读者评论

评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。

0/1500

暂无评论,欢迎抢沙发。