2017年2月22日水曜日

[Python3] Google Custom Search API を試す

# pylint: disable-msg=C0103

"""
Google Custom Search API を Python3 から実行する
"""
import sys
import urllib.request
import urllib.parse
import json

apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
engineid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
query = urllib.parse.quote_plus('長澤まさみ', encoding='utf8')

url = ('https://www.googleapis.com/customsearch/v1?'
       'key=%s&cx=%s&searchType=image&q=%s') % (apikey, engineid, query)

try:
    response = urllib.request.urlopen(url)
    result = json.loads(response.read().decode('utf8'))
except urllib.error.HTTPError as httperr:
    print(httperr)
    sys.exit(1)

# 検索結果よりイメージのタイトルとリンクを表示する
for item in result['items']:
    print(item['title'])
    print(item['link'])
    #print(item['image']['thumbnailLink'])

0 件のコメント:

コメントを投稿