PythonとGoogle Search APIを組み合わせることで、Googleの検索結果をプログラムで取得することが可能です。これは、ウェブスクレイピングやデータ分析、SEO対策など、様々な用途で活用できます。
Google Search APIの概要
Google Search APIは、Googleの検索結果を取得するためのAPIです。このAPIを使用すると、特定のキーワードに対する検索結果をJSON形式で取得できます。
PythonとGoogle Search APIの連携
PythonでGoogle Search APIを使用するためには、まずGoogle Cloud PlatformでAPIキーを取得する必要があります。次に、Custom Search EngineのIDを取得します。これらの情報を使って、Pythonのgoogleapiclient
ライブラリを通じてAPIを呼び出すことができます。
以下に、PythonでGoogle Search APIを使用して検索結果を取得するサンプルコードを示します。
import datetime
import json
from time import sleep
from googleapiclient.discovery import build
GOOGLE_API_KEY = "YOUR_API_KEY"
CUSTOM_SEARCH_ENGINE_ID = "YOUR_SEARCH_ENGINE_ID"
def get_search_results(keyword):
service = build("customsearch", "v1", developerKey=GOOGLE_API_KEY)
response = service.cse().list(
q=keyword,
cx=CUSTOM_SEARCH_ENGINE_ID,
lr='lang_ja',
num=10
).execute()
return response
if __name__ == '__main__':
keyword = 'Python'
results = get_search_results(keyword)
print(json.dumps(results, indent=2, ensure_ascii=False))
このコードは、指定したキーワードに対するGoogleの検索結果を取得し、結果をJSON形式で出力します。
まとめ
PythonとGoogle Search APIを活用することで、Googleの検索結果をプログラムで取得し、自動化やデータ分析などに活用することが可能です。ただし、Google Search APIの利用には制限があるため、大量のデータを取得する場合は注意が必要です。