ahrefs-python について
ahrefs-pythonは、Ahrefs APIからSEOやウェブ分析データを取得するPython SDKのスキルです。型付きのリクエスト・レスポンスモデルに加え、検索語からAPIメソッドのシグネチャやパラメーターを探す機能を備えています。
主な機能
- 01被リンク、キーワード、ドメイン指標の取得
- 02順位追跡、サイト監査、SERPデータの取得
- 03ブランド言及とウェブトラフィックの分析
- 04Rank Trackerプロジェクトとキーワードリストの管理
- 05APIメソッド、パラメーター、戻り値の検索
活用シーン
- 01ドメインの被リンクと自然検索キーワードの調査
- 02検索順位と競合の追跡
- 03サイトの技術的なSEO課題の確認
- 04ウェブトラフィックとブランド言及の調査
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ ahrefs/ ahrefs-api-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 - キーワード調査、検索ボリューム、難易度、関連語
- Management — Rank Tracker のプロジェクト、キーワードリスト、競合他社、および Brand Radar のプロンプトの管理(作成、更新、削除)
- Rank Tracker - SERP モニタリング、競合他社の追跡
- Site Audit - 技術的な SEO の問題、ページコンテンツ、ページエクスプローラー
- Brand Radar - AI におけるブランドへの言及、シェア・オブ・ボイス、インプレッション
- SERP Overview - 検索結果の分析
- Batch Analysis - POST によるドメイン/URL 指標の一括取得
- Web Analytics - ウェブサイト訪問者の分析(トラフィック、ブラウザー、デバイス、流入元、ページ)
- Public — Ahrefs クローラーの IP アドレスと CIDR 範囲(API キーは不要)
- Subscription Info — API の使用制限、請求期間、キーの有効期限
インストール
pip3 install git+https://github.com/ahrefs/ahrefs-python.git
Python 3.11 以降が必要です。依存関係:httpx、pydantic。
API メソッドの検索
SDK には、11 の API セクションにまたがる 105 個のメソッドがあります。適切なメソッドを見つけるには、組み込みの検索ツールが最も手早い方法です。該当するメソッドのシグネチャ、パラメーター、戻り値の型が直接返されるため、大規模なリファレンスを調べる必要はありません。
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-pythonSDK を使用してください。Ahrefs API に対して生のhttpx/requests呼び出しを行わないでください。 - 日付は必ず
YYYY-MM-DD形式の文字列(例:"2025-01-15")で渡してください。 - リストエンドポイントでは、必要な列だけをリクエストするため、必ず
selectを使用してください。リストエンドポイントはデフォルトですべての列を返すため、API ユニットを無駄に消費し、レスポンスサイズも大きくなります。 - クライアントのライフサイクル管理には、コンテキストマネージャー(
with/async with)を使用してください。 - 複数の独立した API 呼び出しを行う場合は、
asyncio.gather()とAsyncAhrefsClientの使用を優先してください。並列処理により、実時間と API の往復回数を削減できます。 - 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
公開エンドポイントは API キーなしで動作します。api_key パラメーターを省略してください。
from ahrefs import AhrefsClient
with AhrefsClient() as client:
ips = client.public_crawler_ips()
ranges = client.public_crawler_ip_ranges()
キーなしで動作するのは public_* メソッドだけです。それ以外のすべてのメソッドには認証が必要です。認証済みのクライアントから公開メソッドを呼び出すこともできます。別のクライアントや生の HTTP 呼び出しは必要ありません。
SDK のパターン
クライアントのセットアップ
import os
import ahrefs
with ahrefs.AhrefsClient(
api_key=os.environ["AHREFS_API_KEY"], # omit for public-only access
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 を継承します。
エラーが発生し、API キーが有効な場合は、原因を特定するために subscription_info_limits_and_usage() を呼び出してください。サブスクリプションプラン、キーの有効期限、使用量と制限が返されます。403 エラーの場合は、正確な理由(ユニット制限、エクスポート行数制限、週あたりのドメイン数制限など)を確認するために、e.response_body も読み取ってください。
共通パラメーター
ほとんどのリストエンドポイントで、以下のパラメーターを使用します。
| パラメーター | 型 | 説明 |
|---|---|---|
target | str | 分析するドメイン、URL、またはパス |
date | str | YYYY-MM-DD 形式の日付 |
date_from / date_to | str | 履歴エンドポイントの日付範囲 |
country | str | 2 文字の国コード(ISO 3166-1 alpha-2) |
select | str | 返す列をカンマ区切りで指定 |
where | str | フィルター式 |
order_by | str | 列と並び順。例:"volume:desc" |
limit | int | 返す結果の最大数 |
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 を参照してください。
推奨されるデフォルト値
ユーザーから別の指定がない限り、以下を使用してください。
- バックリンクエンドポイント(
all_backlinks、anchors、pages_by_backlinks、refdomains):現在のライブデータにはhistory="live"を使用してください。API のデフォルトはall_timeで、失われたバックリンクも含まれます。 - トラフィック/キーワードエンドポイント(
organic_keywords、top_pages、metricsなど):dateパラメーターには今日の日付を使用してください。
API メソッド
キーワードからメソッドを探すには、search_api_methods("query") または python3 -m ahrefs.api_search "query" を使用してください。検索対象は 11 の API セクションにまたがる全 105 メソッドで、完全なシグネチャ、パラメーター、レスポンスフィールドが返されます。フィールドのリストが非常に長い結果(例:608 フィールドの site_audit_page_explorer)は 9K 文字で省略されます。... [truncated] と表示された場合は、フィールドの完全なリストに頼るのではなく、select を使って必要な列だけを指定してください。
ウェブアナリティクス
ウェブアナリティクスには、多くのディメンションにまたがる 34 のエンドポイントがあります。メソッド名がディメンション名と直接一致するとは限りません(例:ページデータには web_analytics_pages ではなく web_analytics_top_pages を使用します)。正しいメソッドを見つけるには、必ず search_api_methods("web analytics <topic>") を使用してください。
これらのエンドポイントには target ドメインではなく project_id が必要です。日時範囲の指定には from_ と to を使用してください。from は Python の予約語であるため、SDK では from_ を使い、正しい API 名に自動シリアライズします。
# Overall traffic stats (scalar endpoint)
stats = client.web_analytics_stats(project_id=123)
print(stats.pageviews, stats.visitors, stats.visits)
# Dimension breakdown (list endpoint — use select)
browsers = client.web_analytics_browsers(
project_id=123,
from_="2025-01-01T00:00:00Z",
to="2025-01-31T23:59:59Z",
select="browser,visitors",
limit=10,
)
# Time-series chart (list endpoint — requires granularity)
chart = client.web_analytics_chart(
project_id=123,
granularity="daily",
from_="2025-01-01T00:00:00Z",
to="2025-01-31T23:59:59Z",
)
管理
管理エンドポイントでは、Rank Tracker のプロジェクト設定と Brand Radar のプロンプト管理(プロジェクトの作成、キーワードリストの管理、競合他社の追加、カスタム Brand Radar プロンプトの管理)を行います。他の API セクションとは異なり、このセクションには PUT/POST/PATCH/DELETE で状態を変更するエンドポイントが含まれています。これらのエンドポイントでは select、where、order_by、limit は使用しません。
management_projects()を使ってすべてのプロジェクトを一覧表示し、project_idの値を確認してください。- キーワードを追加する前に、
management_locations()を使って有効な国コード、言語コード、ロケーション ID を取得してください。 keyword_list_idは API から取得できません。ユーザーが Ahrefs のウェブ UI から指定する必要があります。キーワードリストのメソッドは、management_keyword_list_keywords(一覧表示)、management_set_keyword_list_keywords(PUT で追加)、management_keyword_list_keywords_delete(削除)です。- Brand Radar のプロンプトエンドポイントには、Brand Radar レポートの URL から取得する
report_idが必要です。メソッドはmanagement_brand_radar_prompts(一覧表示)、management_create_brand_radar_prompts(作成)、management_brand_radar_prompts_delete(削除)です。 - 削除エンドポイントの操作は破壊的で、元に戻せません。
management_project_keywords_delete、management_project_competitors_delete、management_keyword_list_keywords_delete、management_brand_radar_prompts_deleteを呼び出す前に、必ずユーザーに確認してください。
# List all Rank Tracker projects
projects = client.management_projects()
for p in projects:
print(p.project_id, p.project_name, p.url)
# Add keywords to a project (requires nested request types)
from ahrefs.types import ManagementSetProjectKeywordsLocation, ManagementSetProjectKeywordsKeyword
client.management_set_project_keywords(
project_id=12345,
locations=[ManagementSetProjectKeywordsLocation(
country="us",
language="en",
)],
keywords=[ManagementSetProjectKeywordsKeyword(keyword="ahrefs seo")],
)
# Add competitors to a project
from ahrefs.types import ManagementCreateProjectCompetitorsCompetitor
client.management_create_project_competitors(
project_id=12345,
competitors=[ManagementCreateProjectCompetitorsCompetitor(
url="moz.com",
mode="domain",
)],
)
# List Brand Radar custom prompts
prompts = client.management_brand_radar_prompts(report_id="abc123")
for p in prompts:
print(p.prompt, p.country, p.created_at)
# Create custom prompts for specific countries
client.management_create_brand_radar_prompts(
report_id="abc123",
countries=["us", "gb"],
prompts=["What is the best SEO tool?"],
)