![](https://clione33.online/wp-content/uploads/2022/12/worried_man01-150x150.png)
Google Search ConsoleのAPIの使い方を教えて!
マーケティングの実務や、ブログの運営には欠かすことのできないGoogle Search Console(以下、サーチコンソール)。
今回は、そんなGSCのデータをPythonで自動で取得する方法をお伝えしていきます。
とても簡単にできるのに、便利すぎるので、ぜひ試してみてください。
Google Search Consoleのユーザーを追加する権限が必要になるため予めご注意ください。
その①:Google Search Console APIを有効にする
まずは、上記のURLから、Google Search Consoleを検索。
![Google Search Console APIライブラリ 手順](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-04-2-1024x439.png)
![Google Search Console APIライブラリ 手順](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-04-2-1024x439.png)
![Google Search Console APIライブラリ 手順](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-05-2-1024x401.png)
![Google Search Console APIライブラリ 手順](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-05-2-1024x401.png)
Google Search Console APIを有効にします。
(画像ではすでに有効にしているため「管理」と表示されています。)
![Google Search Console APIライブラリ 有効](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-11-2-1024x454.png)
![Google Search Console APIライブラリ 有効](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-11-2-1024x454.png)
その②:Google Cloud Platformのプロジェクト鍵の発行
PythonでGoogle APIと連携するための「鍵」を作成します。
画像の通り、「サービスアカウント」→「キー」→「鍵を追加」→「新しい鍵を作成」の順に進めます。
![Google Search Console APIライブラリ サービスアカウント 新しい鍵を作成](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-07-2-1024x633.png)
![Google Search Console APIライブラリ サービスアカウント 新しい鍵を作成](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-07-2-1024x633.png)
キータイプはJSONにして、作成。
![Google Search Console API 秘密鍵の作成](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-08-2-1024x488.png)
![Google Search Console API 秘密鍵の作成](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-08-2-1024x488.png)
jsonファイルがダウンロードされるはずなので、ファイル名をclient_secret.jsonに変更して、大切に保管してください。
より詳しい解説は以下の記事で書いていますので、よければこちらも参考にしてください。
![](https://clione33.online/wp-content/uploads/2021/09/210918_python_gas_gmailapi_oauth1-300x158.png)
![](https://clione33.online/wp-content/uploads/2021/09/210918_python_gas_gmailapi_oauth1-300x158.png)
その③:Google Search Consoleの権限追加
続いて、サーチコンソールのユーザーを追加します。
ここで、さきほどダウンロードしたjsonファイルに記載されているメールアドレスを使用します。
![Google Cloud Platform GoogleSheetsAPI jsonファイル client_email](https://clione.online/wp-content/uploads/2021/09/googlecloudplatform23_02.png)
![Google Cloud Platform GoogleSheetsAPI jsonファイル client_email](https://clione.online/wp-content/uploads/2021/09/googlecloudplatform23_02.png)
サーチコンソールを開いて、右側の設定。
![Google Search Console 設定](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-09-2-1024x667.png)
![Google Search Console 設定](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-09-2-1024x667.png)
ユーザーと権限→ユーザーを追加をクリック。
![Google Search Console ユーザー追加](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-12-2-1024x440.png)
![Google Search Console ユーザー追加](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-12-2-1024x440.png)
jsonファイルに記載されているアドレスをユーザーに追加します。
権限はフルにして追加をクリック。
![Google Search Console ユーザーを追加 メールアドレス 権限](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-13-2-1024x577.png)
![Google Search Console ユーザーを追加 メールアドレス 権限](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-13-2-1024x577.png)
ここまでで、下準備が完了です。
その④:Pythonでサーチコンソールのデータ取得
今回は、AnacondaのJupyter Notebookを使用しました。
Google APIライブラリインストール
もしもGoogle APIを初めて使う方は以下のライブラリをインストールする必要があります。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
pip install --upgrade oauth2client --ignore-installed six
スクリプトの作成(初期設定)
まずは必要な設定をしていきます。
ライブラリのインポート。
import pandas as pd
import numpy as np
import os
Anacondaを使ったので、ディレクトリの設定。(今回はデスクトップで作業をしました。)
#set directories
wd = os.getcwd()
Google API ライブラリのインポート。
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
scopeとjsonファイルの読み込み。
scope = ["https://www.googleapis.com/auth/webmasters","https://www.googleapis.com/auth/webmasters.readonly"]
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
webmasters = build('webmasters', 'v3', credentials=creds)
以下は、notebook上の画像です。
![Google Search Console API Python](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-01-1024x256.png)
![Google Search Console API Python](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-01-1024x256.png)
スクリプトの作成(GSCの連携)
サーチコンソールのデータを取得します。
今回は、2022年4/1-30までのサーチコンソールのデータを取得しています。
site = 'https://clione.online' #あなたのサイトURL
dimensions = ['query', 'page']
startDate = '2022-04-01'
endDate = '2022-04-30'
rowLimit = 100 #取得件数
body = {
'startDate': startDate,
'endDate': endDate,
'dimensions': dimensions,
'rowLimit': rowLimit
}
response = webmasters.searchanalytics().query(siteUrl=site, body=body).execute()
df = pd.io.json.json_normalize(response['rows'])
for i, d in enumerate(dimensions):
df[d] = df['keys'].apply(lambda x: x[i])
df.drop(columns='keys', inplace=True)
df.to_csv('{}.csv'.format(startDate), index=False)
print(df)
![Google Search Console API Python](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-02-1024x373.png)
![Google Search Console API Python](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-02-1024x373.png)
サイトURLと日付、取得件数は適宜、変更してください。
実行結果
無事にサーチコンソールのデータが取得できています。
![Google Search Console API Python データ取得](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-03-2-1024x780.png)
![Google Search Console API Python データ取得](https://clione.online/wp-content/uploads/2022/05/gas-search-console-setting-03-2-1024x780.png)
これでデータの取得が完了です。
作業中のディレクトリに、csvファイルができているはずなので、そちらもチェックしてみてください。
もしも、Mac環境で、CSVが文字化けする場合は、最後から2行目のコードに、encodingを足してください。
df.to_csv('{}.csv'.format(startDate), index=False, encoding='utf_8_sig')
【注意】HttpError 403のエラーが出る場合
HttpError: <HttpError 403 when requesting
"You do not own this site, or the inspected URL is not part of this property."
Details: "You do not own this site, or the inspected URL is not part of this property."
もしも上記のようなエラーが出た場合は以下のことをチェックしてみてください。
1:URLの部分をドメインにしていないか
site = 'https://clione.online' #あなたのサイトURL
ここはドメインではなく、URLなので注意してください。
2:URLを間違って記載していないか
そもそもスペルを間違っていないか改めて確認してください。
3:サーチコンソールのユーザー追加をしているか。
しっかりユーザーの権限を付与できているか、改めて確認してください。
まとめ
今回は、Google APIとPythonを使って、Google Search Consoleのデータを取得する方法をご紹介しました。
自動レポートを使うことで、日々のレポート業務がかなり楽になるはずです。
マーケターやブログ運営をしている方は、使えて絶対に損はないスキルなのでぜひ試してみてください。
コメント