2016-02-02 14 views

Trả lời

6

Tôi nghĩ rằng bạn đang tìm kiếm urllib.pathname2url. Hãy so sánh:

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' 

Các hành vi có vẻ tương tự với tôi, nhưng họ có thể tinh tế khác nhau.

Edit:

Đang đọc nhận xét của bạn về bài Algina, tôi nghĩ rằng đây là cách ưa thích của tôi để xây dựng các url:

>>> 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

Cảm ơn, tôi sẽ thử rằng – timothylhuillier

0

Bạn có thể cụ thể hơn không? bạn có urllib.parse.quote_plus(...) urllib.parse.quote_from_bytes(...) urllib.parse.unquote(...) như bạn đề cập

see doc ở đây: https://docs.python.org/3.2/library/urllib.parse.html

+0

Cảm ơn, Tôi có 'req = 'http://dev.echonest.com/api/v4/song/search?api_key=xxxx&format=json&artist=' + urllib.parse.quote (nghệ sĩ)' Và 'artist =" Oasis "' – timothylhuillier

3

thực sự sử dụng thư viện six, được thực hiện cho python2/tương thích python3 bạn có thể làm

import six.moves.urllib as urllib 

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

và nếu bạn chỉ muốn python2, nó thực sự là urllib.quote di trực tiếp

+0

Cảm ơn bạn đã cho mẹo này! –

+0

Hi @ allan.simon, tôi đã cài đặt gói 'sáu (1.10.0)' và tôi nhận được 'AttributeError: 'Module_six_moves_urllib' đối tượng không có thuộc tính 'quote'' .. Bất kỳ ý tưởng tại sao? –

+0

Dường như tôi cần 'urllib.parse.quote (...)' (thực ra trong trường hợp của tôi, tôi cần 'urllib.parse.quote_plus (...)'). –

Các vấn đề liên quan