235:URLをエンコードする/デコードする
URLとして使える文字には制限があります。ひらがな、カタカナや漢字を含む文字列をURLにそのまま入れてはいけません。
そのような文字列をURLに含めるためには、urllibモジュールのquote_plus関数を用います。
http://www.python.jp/doc/release/lib/module-urllib.html
これをデコードするには、unquote_plusを使います。
>>> import urllib
>>> str=u'た のしい&Python&レシピ'
>>> print str
た のしい&Python&レシピ
>>> url='http://lightson.dip.jp/zope/'+urllib.quote_plus(str.encode('utf-8'),safe='/')
>>> print url
http://lightson.dip.jp/zope/%E3%81%9F+%E3%81%AE%E3%81%97%E3%81%84%26Python%26%E3%83%AC%E3%82%B7%E3%83%94
>>> print urllib.unquote_plus(url)
http://lightson.dip.jp/zope/た のしい&Python&レシピ
qutote_plusだとスペースは+に変換されますが、quoteでは%20になります。
>>> url2='http://lightson.dip.jp/zope/'+urllib.quote(str.encode('utf-8'))
>>> print url2
http://lightson.dip.jp/zope/%E3%81%9F%20%E3%81%AE%E3%81%97%E3%81%84%26Python%26%E3%83%AC%E3%82%B7%E3%83%94
>>> print urllib.unquote(url2)
http://lightson.dip.jp/zope/た のしい&Python&レシピ
クエリ文字列を作るなら、urlencode()がお薦めです。
連想検索エンジンに文字列を渡してキーワードを取り出す例です。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
def get_warp_words(keyword=u'クワガタ'):
urlprefix = 'http://labs.preferred.jp/reflexa/api.php?'
query = [('q', keyword.encode('utf-8')),('format','json')]
# print urllib.quote(keyword.encode('utf-8'))
url = urlprefix + urllib.urlencode(query) # urlencodeでquery文字列を作る
print url
src = urllib.urlopen(url).read()
src = src.strip()[1:-1]
words = src.split(',')
word_lst = []
for word in words:
word_lst.append(unicode(word.strip('"') ,'unicode-escape'))
return word_lst
for word in get_warp_words(u'山本潤子'):
print word