目的
PythonからWeb apiを呼び出す練習として、Yahoo のローカルmap Apiを使ったが、ちょっと詰まったので共有
前提
- Windows 10
- Python 3.7.3
コード
import urllib.request
import urllib.parse
import urllib.error
serviceurl = 'https://map.yahooapis.jp/search/local/V1/localSearch?'
searchWord = input('検索ワード:')
encodeSearchWord = searchWord.encode()
# param作成
parms = dict()
parms['appid'] = 'dj00aiZpPWJjSkFpcHQ2WlJmZSZzPWNvbnN1bWVyc2VjZXZXZng9MjM-'#プライバシー保護のため一部変更してます
parms['query'] = encodeSearchWord
parms['results'] = 100
parms['output'] = 'xml'
url = serviceurl + urllib.parse.urlencode(parms)
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
# print(data[:200])
# 書き込み
file = open('result.xml', 'w', encoding='UTF-8')
file.write(data)
file.close()
解説
基本的に以下の公式url通りで問題ない
url:https://developer.yahoo.co.jp/webapi/map/openlocalplatform/v1/localsearch.html
ただし、以下の注意が必要
- アプリケーションId(コードのappid)は、確認画面では「ClientId」と記載されているため、アプリケーションIdどこや!となる
- 検索ワードはencode(searchWord.encode())しないといけない。str型ではだめ
ほかにもいろいろな検索パラメータがあるので、興味のある人はぜひ