首頁  >  文章  >  後端開發  >  如何在 Python 中正確編碼 URL 參數:解決 `urllib.quote()` 和 `urllib.urlencode()` 的限制

如何在 Python 中正確編碼 URL 參數:解決 `urllib.quote()` 和 `urllib.urlencode()` 的限制

Barbara Streisand
Barbara Streisand原創
2024-10-26 03:28:03191瀏覽

How to Properly Encode URL Parameters in Python:  Addressing Limitations of `urllib.quote()` and `urllib.urlencode()`

在Python 中使用百分比編碼對URL 參數進行編碼

當對URL 參數進行百分比編碼以防止錯誤並確保百分比規範化時,內建的urllib.quote() 函式中可能會出現不足。

預設編碼遺漏:

如下使用urllib.quote():

url = "http://example.com?p=" + urllib.quote(query)

省略將/ 等關鍵字元編碼為/ ,這會導致OAuth 規範化出現問題。

Unicode 支援缺陷:

此外,它無法處理 Unicode 字串,導致嘗試編碼非 ASCII 字元時出現異常。

使用 urllib.parse.quote() 和安全參數改進編碼:

要解決這些限制,請使用 urllib。 Python 3 中的parse.quote() 提供了一個解決方案:

urllib.parse.quote(string, safe='/', encoding=None, errors=None)

安全參數預設為'/',但指定空字串會停用額外的ASCII 字元排除,從而確保/ 的正確編碼:

urllib.parse.quote('/test', safe='') # Encodes '/' to '%2F'

修正Python 2 中的Unicode 處理:

在Python 2 中,urllib.quote() 存在Unicode 處理錯誤。要解決此問題,請在應用百分比編碼之前將字串手動編碼為UTF-8:

query = urllib.quote(u"Müller".encode('utf8'))
print urllib.unquote(query).decode('utf8') # Outputs: Müller

替代方案: urllib.urlencode()

對於更簡單的方法,請考慮使用urllib.urlencode(),它自動處理百分比編碼和Unicode:

encoded_params = urllib.urlencode({'p': query}) # Properly encodes '/' and supports Unicode

以上是如何在 Python 中正確編碼 URL 參數:解決 `urllib.quote()` 和 `urllib.urlencode()` 的限制的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn