364

如果我做

url = "http://example.com?p=" + urllib.quote(query)
  1. 它不编码/%2F(破坏 OAuth 规范化)
  2. 它不处理 Unicode(它会引发异常)

有更好的图书馆吗?

4

5 回答 5

471

蟒蛇2

文档中

urllib.quote(string[, safe])

使用 %xx 转义符替换字符串中的特殊字符。从不引用字母、数字和字符“_.-”。默认情况下,此函数用于引用 URL 的路径部分。可选的安全参数指定不应引用的附加字符 -它的默认值为 '/'

这意味着通过安全''将解决您的第一个问题:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

关于第二个问题,有一个关于它的错误报告。显然它已在 Python 3 中修复。您可以通过编码为UTF-8来解决它,如下所示:

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

顺便说一下,看看urlencode

蟒蛇 3

在 Python 3 中,该函数quote已移至urllib.parse

>>> import urllib.parse
>>> print(urllib.parse.quote("Müller".encode('utf8')))
M%C3%BCller
>>> print(urllib.parse.unquote("M%C3%BCller"))
Müller
于 2009-11-08T02:52:22.797 回答
200

在 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/'
于 2012-11-29T11:52:51.430 回答
63

我认为模块requests要好得多。它基于urllib3.

你可以试试这个:

>>> from requests.utils import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'

我的回答与Paolo 的回答类似。

于 2015-07-14T08:30:58.440 回答
15

如果您使用的是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)
于 2015-10-27T19:40:21.020 回答
5

最好在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

文档

于 2018-11-29T15:46:05.410 回答