Google Search Console APIをPythonで使用する方法
更新日: by Heysho
この記事では、Google Search Console(サーチコンソール) のデータをPythonで分析するために、Google Search ConsoleのAPIを利用する方法を解説します。簡単な流れは以下の通りです。
- Google Cloud でプロジェクトを作成
- Google Cloud でSearch ConsoleのAPIを有効化し、認証用のキーを取得する
- Google Colabでアカウント同士を認証させる
- データを取得
それでは、行ってみましょう!
STEP 1. Google Cloud でプロジェクトを作成
Google Cloud Platformにアクセスし、新しいプロジェクトを作成します。

STEP 2. Search ConsoleのAPIを有効化する
プロジェクトが作成できたら、Search Console APIを有効化し、認証用のクレデンシャルを設定します。





STEP 3. OAuth consent screenを作成
OAuth同意画面を設定し、アプリケーションの認証設定を行います。







STEP 4. Credentialsを作成
認証に必要なClient IDとClient Secretを取得するため、OAuth 2.0のクレデンシャルを作成します。





STEP 5. Google Colabで読み込む
# Install required python packages
!pip install oauth2client
!pip install google-api-python-client
!pip install httplib2
# Import required packages
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build
import httplib2
CLIENT_ID = "★Google Cloudで取得したClient Secretを貼り付け★"
CLIENT_SECRET = "★Google Cloudで取得したClient Secretを貼り付け★"
# Define Oath scopes with read only access
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
# OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters'
# Redirect URI to open Authorization Code Window in Browser
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Build URL that generates Authorization Code
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
#Print Authorization URL
print("Go to the following link in your browser: " + authorize_url)
STEP 6. Google Colabのアカウントと、Google Cloudのアカウントを認証させる
認証URLにアクセスし、表示されるAuthorization codeをコピーします。


STEP 7. Search Console APIが読み込めているか確認
auth_code = "★さっきコピーしたAuthorization codeを貼り付ける★"
credentials = flow.step2_exchange(auth_code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
#authorize credentials
creds = credentials.authorize(http)
#building a service to access various features of GSC API
webmasters_service = build('searchconsole', 'v1', http=creds)
webmasters_service
<googleapiclient.discovery.Resource at ◯◯◯◯> というメッセージが返ってきたらOKです。
STEP 8. 日別データを抽出
# the website we want to get the data for
website = "https://heysho.com/"
# build a request body
request_body = {
"startDate" : '2024-01-01',
"endDate" : '2024-02-28',
"dimensions" : [],
"rowLimit" : 25000,
"dataState" : "final"
}
# get the response using request body
response_data = webmasters_service.searchanalytics().query(siteUrl=website, body=request_body).execute()
for each in response_data:
print(each)
これで日別のデータが返ってきたら成功です。
まとめ
セットアップのみになりましたが、本格的な分析も後日追記します。参考になれば幸いです。ご精読ありがとうございました。