mcpField
A
ahrefs-python

ahrefs-python

github.com/openclaudiaマーケティング・グロース722318 回インストール1 週間前に更新
リポジトリ

ahrefs-python について

ahrefs-pythonはAhrefsのSEOデータAPIを利用するPython SDKです。PythonプログラムやコマンドラインからSEO指標を調べる開発者向けに、型付きデータモデルとメソッド検索機能を備えています。

主な機能

  1. 01被リンク・キーワード・トラフィックの取得
  2. 02順位追跡とサイト監査データへのアクセス
  3. 03Brand RadarとSERPデータの取得
  4. 04型付きリクエスト・レスポンスモデル
  5. 05APIメソッドとパラメーターの検索

活用シーン

  1. 01ドメインやURLの指標を一括分析
  2. 02Pythonプロジェクトでキーワードを調査
  3. 03検索順位と競合を追跡
  4. 04コマンドラインからSDKメソッドを検索

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/openclaudia/openclaudia-skills --skill ahrefs-python

インストール後、Claude Code で/ahrefs-pythonを入力して読み込まれたか確認します。

同梱ファイルreferences/api-methods.mdreferences/filter-syntax.md

詳細

Ahrefs Python SDK スキル

概要

Ahrefs API を使用すると、Ahrefs の SEO データにプログラムからアクセスできます。公式 Python SDK(ahrefs-python)は、OpenAPI 仕様から自動生成された、すべてのエンドポイント用の型付きリクエストモデルとレスポンスモデルを提供します。

主な機能:

  • Site Explorer - 被リンク、オーガニックキーワード、ドメインレーティング、トラフィック、参照ドメイン
  • Keywords Explorer - キーワード調査、検索ボリューム、難易度、関連語句
  • Rank Tracker - SERP のモニタリング、競合他社の追跡
  • Site Audit - テクニカル SEO の問題、ページコンテンツ、ページエクスプローラー
  • Brand Radar - AI によるブランドへの言及、声のシェア、インプレッション
  • SERP Overview - 検索結果の分析
  • Batch Analysis - POST によるドメイン/URL 指標の一括取得

インストール

pip3 install git+https://github.com/ahrefs/ahrefs-python.git

Python 3.11 以降が必要です。依存関係:httpx、pydantic。

API メソッドの検索

SDK には、7 つの API セクションにわたる 52 個のメソッドがあります。適切なメソッドを探すには、組み込みの検索ツールを使うのが最も手早い方法です。該当するメソッドのシグネチャ、パラメーター、戻り値の型が直接返されるため、膨大なリファレンスを確認する必要はありません。

Python(すでに Python 環境を使用している場合に推奨):

from ahrefs.search import search_api_methods

# Returns formatted text with method signatures, parameters, and return types
print(search_api_methods("domain rating"))

# Filter by API section and limit results
print(search_api_methods("backlinks", section="site-explorer", limit=3))

CLI(ターミナルから調べる場合に推奨):

# Ensure python3 points to the interpreter where ahrefs-python is installed:
#   which python3
#   python3 -c "import ahrefs"
python3 -m ahrefs.api_search "domain rating"
python3 -m ahrefs.api_search "backlinks" --section site-explorer --limit 3
python3 -m ahrefs.api_search "batch" --json
python3 -m ahrefs.api_search --sections  # list all API sections

重要なルール

  • 必ず ahrefs-python SDK を使用してください。Ahrefs API への httpx/requests による直接呼び出しは行わないでください。
  • 日付は必ず YYYY-MM-DD 形式の文字列で指定してください(例:"2025-01-15")。
  • リストエンドポイントでは、必要な列だけをリクエストするために必ず select を使用してください。リストエンドポイントはデフォルトですべての列を返すため、API ユニットを無駄に消費し、レスポンスサイズも大きくなります。
  • クライアントのライフサイクル管理には、コンテキストマネージャー(with/async with)を使用してください。
  • API キーをソースコードにハードコードしないでください。AHREFS_API_KEY 環境変数、またはお好みのシークレット管理方法を使用してください。
  • クライアントはリトライ(429、5xx、接続エラー)を自動で処理します。SDK の上に独自のリトライロジックを実装しないでください。

クイックスタート

import os
from ahrefs import AhrefsClient

with AhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
    print(data.domain_rating)  # 91.0
    print(data.ahrefs_rank)    # 3

SDK のパターン

クライアントのセットアップ
import os
import ahrefs

with ahrefs.AhrefsClient(
    api_key=os.environ["AHREFS_API_KEY"],  # or any secrets source
    base_url="...",          # override API base URL (default: https://api.ahrefs.com/v3)
    timeout=30.0,            # request timeout in seconds (default: 60)
    max_retries=3,           # retries on transient errors (default: 2)
) as client:
    ...

非同期クライアント:

import os
from ahrefs import AsyncAhrefsClient

async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    data = await client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")

並列呼び出しには asyncio.gather を使用します:

import asyncio

async with AsyncAhrefsClient(api_key=os.environ["AHREFS_API_KEY"]) as client:
    dr_ahrefs, dr_moz = await asyncio.gather(
        client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15"),
        client.site_explorer_domain_rating(target="moz.com", date="2025-01-15"),
    )
メソッドの呼び出し

2 種類の呼び出し方法があります。どちらも同じ動作です:

# Keyword arguments (recommended)
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")

# Request objects (full type safety)
from ahrefs.types import SiteExplorerDomainRatingRequest
request = SiteExplorerDomainRatingRequest(target="ahrefs.com", date="2025-01-15")
data = client.site_explorer_domain_rating(request)

メソッド名は {api_section}_{endpoint} の形式です。例:site_explorer_organic_keywords、keywords_explorer_overview。

レスポンス

メソッドは型付きの Data オブジェクトを直接返します。

スカラーエンドポイントは単一のデータオブジェクト(または None)を返します:

data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
print(data.domain_rating)

リストエンドポイントはデータオブジェクトのリストを返します。ページネーションはありません。必要な結果数を limit に設定してください。必要な列だけをリクエストするには select を使用します:

items = client.site_explorer_organic_keywords(
    target="ahrefs.com",
    date="2025-01-15",
    select="keyword,volume,best_position",
    order_by="volume:desc",
    limit=10,
)
for item in items:
    print(item.keyword, item.volume, item.best_position)
エラー処理
import ahrefs

try:
    data = client.site_explorer_domain_rating(target="example.com", date="2025-01-15")
except ahrefs.AuthenticationError:    # 401
    ...
except ahrefs.RateLimitError as e:    # 429 -- e.retry_after has the delay
    ...
except ahrefs.NotFoundError:          # 404
    ...
except ahrefs.APIError as e:          # other 4xx/5xx -- e.status_code, e.response_body
    ...
except ahrefs.APIConnectionError:     # network / timeout
    ...

すべての例外は ahrefs.AhrefsError を継承します。

共通パラメーター

ほとんどのリストエンドポイントで、次のパラメーターが共通して使用されます:

パラメーター型説明
targetstr分析するドメイン、URL、またはパス
datestrYYYY-MM-DD 形式の日付
date_from / date_tostr履歴エンドポイントで使用する日付範囲
countrystr2 文字の国コード(ISO 3166-1 alpha-2)
selectstr返す列をカンマ区切りで指定
wherestrフィルター式
order_bystr列と並び順。例:"volume:desc"
limitint返す結果の最大数

API リファレンスで列挙型(CountryEnum、VolumeModeEnum など)として定義されているパラメーターには、通常の文字列を指定できます。CountryEnum("us") ではなく、country="us" のように渡してください。

where パラメーターには JSON 文字列を指定します。json.dumps() を使用して作成してください:

import json
where = json.dumps({"field": "volume", "is": ["gte", 1000]})
items = client.site_explorer_organic_keywords(
    target="ahrefs.com", date="2025-01-15",
    select="keyword,volume", where=where,
)

フィルター構文(ブール結合子、演算子、ネストされたフィールド)の詳細については、references/filter-syntax.md を参照してください。

API メソッド

キーワードでメソッドを検索するには、search_api_methods("query") または python3 -m ahrefs.api_search "query" を使用してください。検索対象は、7 つの API セクションにわたる 52 個すべてのメソッドで、完全なシグネチャ、パラメーター、レスポンスフィールドが返されます。

コメント