2012-01-18 54 views
20

urllib或其他库中是否存在一个简单的方法来执行此任务? URL编码将用不安全的ASCII字符替换为后跟两个十六进制数字的“%”。python中的URL编码

下面是一个输入的一个例子,我的预期输出:

Mozilla/5.0 (Linux; U; Android 4.0; xx-xx; Galaxy Nexus Build/IFL10C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 

Mozilla%2F5.0+%28Linux%3B+U%3B+Android+4.0%3B+xx-xx%3B+Galaxy+Nexus+Build%2FIFL10C%29+AppleWebKit%2F534.30+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Mobile+Safari%2F534.30 

回答

41

对于Python 2.x中,使用urllib.quote

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

例如:

In [1]: import urllib 

In [2]: urllib.quote('%') 
Out[2]: '%25' 

编辑

在你的情况下,为了通过加号来代替空间,你可以使用urllib.quote_plus

例如:

In [4]: urllib.quote_plus('a b') 
Out[4]: 'a+b' 

对于Python 3.x中,使用quote

>>> import urllib 
>>> a = "asdas#@das" 
>>> urllib.parse.quote(a) 
'asdas%23%40das' 

和串空间使用“quote_plus”

>>> import urllib 
>>> a = "as da& s#@das" 
>>> urllib.parse.quote_plus(a) 
'as+da%26+s%23%40das' 
+0

或[urllib.quote_plus](http://docs.python.org/library/urllib.html#urllib.quote_plus),因为OP需要'+'而不是'%20'。 – Avaris 2012-01-18 06:09:55

+2

但为了得到OP要求的内容,使用'urllib.quote_plus'。 – 2012-01-18 06:10:02

1

另外,如果你有多个值的字典,最好的办法做到这一点将是urllib.urlencode

2

请记住,无论urllib.quoteurllib.quote_plus抛出一个错误,如果输入是一个unicode字符串:

s = u'\u2013' 
urllib.quote(s) 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python27\lib\urllib.py", line 1303, in quote 
    return ''.join(map(quoter, s)) 
KeyError: u'\u2013' 

作为回答here on SO,人们必须使用 'UTF-8' 明​​确:

urllib.quote(s.encode('utf-8'))