如何在 Python 中对 URL 参数进行百分比编码?
题
如果我做
url = "http://example.com?p=" + urllib.quote(query)
- 它不编码
/
到%2F
(破坏 OAuth 规范化) - 它不处理 Unicode(它会抛出异常)
有更好的图书馆吗?
解决方案
来自 文档:
urllib.quote(string[, safe])
使用%XX Escape替换字符串中的特殊字符。字母,数字和字符“ _.-”从未引用。默认情况下,此功能旨在引用URL的路径部分。可选的安全参数指定不应引用的其他字符 - 其默认值是'/'
这意味着通过 '' 表示安全将解决您的第一个问题:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
关于第二个问题,有一个关于它的错误报告 这里. 。显然它已在 python 3 中修复。您可以通过编码为 utf8 来解决此问题,如下所示:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
顺便看看 网址编码
笔记 那 urllib.quote
搬去 urllib.parse.quote
在Python3中
其他提示
在Python 3中, urllib.quote
已移至 urllib.parse.quote
它默认处理 unicode。
>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'
我的回答与保罗的回答类似。
我认为模块 requests
好多了。它基于 urllib3
。你可以试试这个:
>>> from requests.utils import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
如果您使用 django,则可以使用 urlquote:
>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'
请注意,自该答案发布以来对 Python 的更改意味着它现在是一个遗留包装器。来自 django.utils.http 的 Django 2.1 源代码:
A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)
最好使用 urlencode
这里。单个参数没有太大区别,但恕我直言,使代码更清晰。(看到一个函数看起来很混乱 quote_plus
!尤其是那些来自其他语言的)
In [21]: query='lskdfj/sdfkjdf/ksdfj skfj'
In [22]: val=34
In [23]: from urllib.parse import urlencode
In [24]: encoded = urlencode(dict(p=query,val=val))
In [25]: print(f"http://example.com?{encoded}")
http://example.com?p=lskdfj%2Fsdfkjdf%2Fksdfj+skfj&val=34
文档
网址代码: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode
报价加: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus