tech.sinayaka.com

PythonでSearch Console APIを叩いてSEO状況を毎日確認する

2026-06-05
2026-06-05
4分
659語
Python PythonSEOSearchConsoleGoogleAPI

Google Search ConsoleをブラウザでポチポチするのをやめてPythonで自動化した。

サイトが複数あると特に面倒で、それぞれ開いてタブを切り替えながら確認していたが、Pythonで叩けばターミナル1本で全サイトまとめて確認できる。

事前準備

認証トークンの取得

Google Cloud ConsoleでSearch Console APIを有効化し、OAuthクライアントIDを作成する。一度ブラウザ認証を済ませると ~/.config/search-console-token.json にトークンが保存される。

以下のライブラリが必要:

pip install google-auth google-auth-oauthlib google-api-python-client

基本的な使い方

登録サイト一覧の取得

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

creds = Credentials.from_authorized_user_file(
    '/Users/yourname/.config/search-console-token.json'
)
service = build('searchconsole', 'v1', credentials=creds)

sites = service.sites().list().execute()
for site in sites.get('siteEntry', []):
    print(site['siteUrl'], '-', site.get('permissionLevel', ''))

月次サマリーの取得

def get_summary(service, site_url, start_date, end_date):
    r = service.searchanalytics().query(
        siteUrl=site_url,
        body={'startDate': start_date, 'endDate': end_date, 'dimensions': []}
    ).execute()
    row = r.get('rows', [{}])[0] if r.get('rows') else {}
    return {
        'clicks':      int(row.get('clicks', 0)),
        'impressions': int(row.get('impressions', 0)),
        'ctr':         row.get('ctr', 0) * 100,
        'position':    row.get('position', 0),
    }

複数サイトを一括確認

sites = [
    ('tech',     'sc-domain:tech.example.com'),
    ('blog',     'sc-domain:blog.example.com'),
]

periods = [
    ('6月', '2026-06-01', '2026-06-30'),
    ('5月', '2026-05-01', '2026-05-31'),
    ('4月', '2026-04-01', '2026-04-30'),
]

for name, site in sites:
    print(f"\n{name} 】")
    for label, s, e in periods:
        d = get_summary(service, site, s, e)
        print(f"  {label}: clicks={d['clicks']:>3}  imp={d['impressions']:>4}  "
              f"CTR={d['ctr']:>5.1f}%  pos={d['position']:>5.1f}")

出力はこんな感じになる:

【 tech 】
  6月: clicks=  2  imp=  40  CTR=  5.0%  pos= 10.0
  5月: clicks=  1  imp=  33  CTR=  3.0%  pos=  8.9

上位クエリの確認

def get_top_queries(service, site_url, start_date, end_date, limit=10):
    r = service.searchanalytics().query(
        siteUrl=site_url,
        body={
            'startDate': start_date,
            'endDate':   end_date,
            'dimensions': ['query'],
            'rowLimit': limit,
            'orderBy': [{'fieldName': 'impressions', 'sortOrder': 'DESCENDING'}],
        }
    ).execute()
    return r.get('rows', [])

for row in get_top_queries(service, site, '2026-05-01', '2026-05-31'):
    q = row['keys'][0]
    print(f"  {q:<30} imp={int(row['impressions'])}  pos={row['position']:.1f}")

日次データで改善効果を確認する

SEO施策を打った後、効果がいつ出たかを日次で追いかけると把握しやすい。

def get_daily(service, site_url, start_date, end_date, page_filter=None):
    body = {
        'startDate': start_date,
        'endDate':   end_date,
        'dimensions': ['date', 'page'] if page_filter else ['date'],
        'orderBy': [{'fieldName': 'date', 'sortOrder': 'ASCENDING'}],
    }
    if page_filter:
        body['dimensionFilterGroups'] = [{
            'filters': [{'dimension': 'page', 'operator': 'contains',
                         'expression': page_filter}]
        }]
    return service.searchanalytics().query(
        siteUrl=site_url, body=body
    ).execute().get('rows', [])

実際に使ってみると、記事を修正した翌日から急にクリックが出始めた、という変化が日次データで一目でわかる。ブラウザで毎日確認するより断然早い。

sc-domain: と https:// の違い

Search Consoleには2種類のプロパティがある。

  • ドメインプロパティsc-domain:example.com):HTTPSもHTTPもサブドメインも全て含む
  • URLプレフィックスプロパティhttps://example.com/):指定URLのみ

複数サブドメインを運用している場合はドメインプロパティの方が一括管理できて便利だ。

まとめ

Search Console APIをPythonで叩くと、複数サイトの状況を数秒で確認できる。ブラウザを開く必要がなくなり、Claude Codeのチャットに貼り付けてAIに分析させることもできる。コードを一度書いておけば毎日のチェックが自動化できる。




Copyright 2026
サイトマップ