LoginSignup
13
10

More than 5 years have passed since last update.

urllib.parse.quote関数使用時の注意

Last updated at Posted at 2013-10-14

URLエンコードする際に使用するurllib.parse.quote関数(Python2ではurllib.quote関数)は、デフォルトではパス区切り文字(/)をエンコード対象にしない。

>>> help(urllib.parse.quote)

# 引数safeで指定された文字列はエンコード対象外となる。
quote(string, safe='/', encoding=None, errors=None)
    quote('abc def') -> 'abc%20def'

(…)

    By default, the quote function is intended for quoting the path
    section of a URL.  Thus, it will not encode '/'.  This character
    is reserved, but in typical usage the quote function is being
    called on a path where the existing slash characters are used as
    reserved characters.

そのため、TwitterAPIなどでURLを含む文字列をエンコードする場合、第二引数(あるいは名前付引数safe)を''(空文字)に設定する必要がある。

quote_safe
# パス区切り文字(/)がエンコードされない
>>> urllib.parse.quote('http://hoge.com/api')
'http%3A//hoge.com/api'

# パス区切り文字(/)がエンコードされる
>>> urllib.parse.quote('http://hoge.com/api', '')
'http%3A%2F%2Fhoge.com%2Fapi'
>>> urllib.parse.quote('http://hoge.com/api', safe='')
'http%3A%2F%2Fhoge.com%2Fapi'
13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10