2016-02-02 154 views

回答

6

我认为你正在寻找urllib.pathname2url。比较:

Python 3中,urllib.parse.quote

>>> urllib.parse.quote('abc def/foo?bar=baz') 
'abc%20def/foo%3Fbar%3Dbaz' 

Python 2中,urllib.pathname2url

>>> urllib.pathname2url('abc def/foo?bar=baz') 
'abc%20def/foo%3Fbar%3Dbaz' 

的行为似乎与我相似,但他们可能会略有不同。

编辑:

上Algina的帖子阅读您的意见,我觉得这是我建立的网址首选方式:

>>> url = 'http://dev.echonest.com/api/v4/song/search' 
>>> params = {'api_key': 'xxxx', 'format': 'json', 'artist': 'Galaxie 500'} 
>>> "{}?{}".format(url, urllib.urlencode(params)) 
'http://dev.echonest.com/api/v4/song/search?api_key=xxxx&artist=Galaxie+500&format=json' 
+0

谢谢,我会尽力 – timothylhuillier

0

你能更具体吗? 你有 urllib.parse.quote_plus(...) urllib.parse.quote_from_bytes(...) urllib.parse.unquote(...) 像你提到的

见文件浏览: https://docs.python.org/3.2/library/urllib.parse.html

+0

谢谢, 我'REQ = 'http://dev.echonest.com/api/v4/song/search?api_key=xxxx&format=json&artist=' + urllib.parse.quote(艺术家)' 和'artist =“Oasis”' – timothylhuillier

3

实际使用图书馆six,这是为python2制作/ python3兼容性,你可以做

import six.moves.urllib as urllib 

# and now you can use urllib as it was python3 
urllib.quote(...) 

,如果你只是想python2,它实际上是urllib.quote迪rectly

+0

谢谢你的提示! –

+0

嗨@ allan.simon,我已经安装了'six(1.10.0)'软件包,并且我得到了'AttributeError:'Module_six_moves_urllib'对象没有属性'quote'' ..任何想法为什么? –

+0

似乎我需要'urllib.parse.quote(...)'(实际上我需要'urllib.parse.quote_plus(...)')。 –