Google Search Console APIをPythonで使用する方法

更新日: by Heysho

この記事では、Google Search Console(サーチコンソール) のデータをPythonで分析するために、Google Search ConsoleのAPIを利用する方法を解説します。簡単な流れは以下の通りです。

  1. Google Cloud でプロジェクトを作成
  2. Google Cloud でSearch ConsoleのAPIを有効化し、認証用のキーを取得する
  3. Google Colabでアカウント同士を認証させる
  4. データを取得

それでは、行ってみましょう!

STEP 1. Google Cloud でプロジェクトを作成

Google Cloud Platformにアクセスし、新しいプロジェクトを作成します。

Google Cloud Platform新規プロジェクト作成画面
Google Cloud Platformで新しいプロジェクトを作成

STEP 2. Search ConsoleのAPIを有効化する

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

Google Cloud APIライブラリ画面
Google Cloud APIライブラリでSearch Console APIを検索
Search Console API検索結果
Search Console APIを選択
Search Console API詳細画面
Search Console APIの詳細画面で「有効にする」をクリック
API有効化確認画面
APIが正常に有効化されたことを確認
認証情報作成画面への移動
「認証情報を作成」をクリックして次のステップへ

STEP 3. OAuth consent screenを作成

OAuth同意画面を設定し、アプリケーションの認証設定を行います。

OAuth consent screen設定画面
OAuth consent screenの設定を開始
ユーザータイプ選択画面
ユーザータイプで「外部」を選択
アプリ情報入力画面
アプリケーション名とユーザーサポートメールを入力
スコープ設定画面
スコープ設定画面(デフォルトのまま進む)
テストユーザー追加画面
テストユーザーに自分のGoogleアカウントを追加
設定内容確認画面
設定内容を確認して完了
OAuth consent screen作成完了
OAuth consent screenの作成が完了

STEP 4. Credentialsを作成

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

認証情報作成開始画面
認証情報の作成を開始
OAuth 2.0クライアントID選択画面
「OAuth 2.0 クライアント ID」を選択
アプリケーションタイプ選択画面
アプリケーションの種類で「デスクトップアプリ」を選択
クライアント名入力画面
クライアント名を入力して作成
認証情報取得完了画面
Client IDとClient Secretが生成されました - これらをコピーして保存

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をコピーします。

Google認証画面
認証URLにアクセスしてGoogleアカウントでログイン
Authorization code表示画面
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)

これで日別のデータが返ってきたら成功です。

まとめ

セットアップのみになりましたが、本格的な分析も後日追記します。参考になれば幸いです。ご精読ありがとうございました。