urlencode處理特殊字符的方法

小樊
84
2024-08-29 08:34:58

urlencode 是一種編碼方式,用于將URL中的特殊字符轉(zhuǎn)換為可傳輸?shù)母袷?。在Python中,你可以使用 urllib.parse.quoteurllib.parse.unquote 函數(shù)進(jìn)行 urlencode 和解碼。

以下是如何使用 urllib.parse.quote 對(duì)特殊字符進(jìn)行編碼的示例:

from urllib.parse import quote

url = "https://www.example.com/search?q=你好,世界!"
encoded_url = quote(url, safe=':/?=')
print(encoded_url)

輸出結(jié)果:

https%3A//www.example.com/search%3Fq%3D%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81

在這個(gè)例子中,我們使用 quote 函數(shù)對(duì)URL進(jìn)行了編碼。safe 參數(shù)用于指定哪些字符不需要被編碼,這里我們?cè)O(shè)置為 ‘:/?=’,表示這些字符保持原樣。

如果你想解碼一個(gè)已編碼的URL,可以使用 urllib.parse.unquote 函數(shù):

from urllib.parse import unquote

encoded_url = "https%3A//www.example.com/search%3Fq%3D%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81"
decoded_url = unquote(encoded_url)
print(decoded_url)

輸出結(jié)果:

https://www.example.com/search?q=你好,世界!

這樣,你就可以使用 urlencode 處理特殊字符了。

0