关于 ahrefs-python
ahrefs-python 是 Ahrefs API 的 Python SDK 技能,面向需要以 Python 获取 SEO 与网站分析数据的开发者。它提供类型化请求与响应模型,并带有方法搜索工具,可按关键词查找 API 签名和参数。
主要功能
- 01查询反向链接、关键词及域名指标
- 02获取排名追踪、站点审计和 SERP 数据
- 03分析品牌提及与网站访问数据
- 04管理排名追踪项目及关键词列表
- 05搜索 API 方法、参数与返回类型
适用场景
- 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 调用时,优先使用
AsyncAhrefsClient和asyncio.gather()——并行处理可以节省实际耗时和 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"),
)
调用方法
两种调用方式——效果相同:
# 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 | 两位国家/地区代码(ISO 3166-1 alpha-2) |
select | str | 要返回的逗号分隔列名 |
where | str | 筛选表达式 |
order_by | str | 列名和排序方向,例如 "volume:desc" |
limit | int | 返回结果的最大数量 |
在 API 参考中类型为枚举的参数(CountryEnum、VolumeModeEnum 等)接受普通字符串——传入 country="us",而不是 CountryEnum("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 仅请求所需列,而不要依赖完整字段列表。
Web Analytics
Web Analytics 在多个维度上共有 34 个端点——并非所有方法名都与维度名称直接对应(例如,页面数据使用 web_analytics_top_pages,而不是 web_analytics_pages)。请始终使用 search_api_methods("web analytics <topic>") 查找正确的方法。
这些端点需要 project_id(而不是 target 域名)。日期时间范围请使用 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。 - 无法通过 API 查找
keyword_list_id——用户必须从 Ahrefs 网页界面提供该 ID。关键词列表方法:management_keyword_list_keywords(列出)、management_set_keyword_list_keywords(通过 PUT 添加)、management_keyword_list_keywords_delete(移除)。 - Brand Radar 提示词端点需要
report_id(来自 Brand Radar 报告 URL)。方法: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?"],
)