ahrefs-python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAhrefs Python SDK Skill
Ahrefs Python SDK 技能文档
Overview
概述
The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK () provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.
ahrefs-pythonKey capabilities:
- Site Explorer - Backlinks, organic keywords, domain rating, traffic, referring domains
- Keywords Explorer - Keyword research, volumes, difficulty, related terms
- Rank Tracker - SERP monitoring, competitor tracking
- Site Audit - Technical SEO issues, page content, page explorer
- Brand Radar - AI brand mentions, share of voice, impressions
- SERP Overview - Search result analysis
- Batch Analysis - Bulk domain/URL metrics via POST
Ahrefs API提供了对Ahrefs SEO数据的程序化访问。官方Python SDK()为所有端点提供了类型化的请求和响应模型,这些模型由OpenAPI规范自动生成。
ahrefs-python核心功能:
- 站点分析工具(Site Explorer) - 反向链接、自然关键词、域名评级、流量、引用域名
- 关键词分析工具(Keywords Explorer) - 关键词研究、搜索量、难度、相关术语
- 排名追踪工具(Rank Tracker) - SERP监测、竞品追踪
- 站点审计工具(Site Audit) - 技术SEO问题、页面内容、页面分析
- 品牌雷达(Brand Radar) - AI品牌提及、声量占比、曝光量
- SERP概览(SERP Overview) - 搜索结果分析
- 批量分析(Batch Analysis) - 通过POST获取批量域名/URL指标
Installation
安装
sh
pip install git+https://github.com/ahrefs/ahrefs-python.gitRequires Python 3.11+. Dependencies: , .
httpxpydanticsh
pip install git+https://github.com/ahrefs/ahrefs-python.git要求Python 3.11及以上版本。依赖库:、。
httpxpydanticIMPORTANT RULES
重要规则
- ALWAYS use the SDK. DO NOT make raw
ahrefs-python/httpxcalls to the Ahrefs API.requests - ALWAYS pass dates as strings in format (e.g.
YYYY-MM-DD)."2025-01-15" - ALWAYS use on list endpoints to request only the columns you need. List endpoints return all columns by default, which wastes API units and increases response size.
select - USE context managers (/
with) for client lifecycle management.async with - SET the environment variable rather than hardcoding API keys.
AHREFS_API_KEY - The client handles retries (429, 5xx, connection errors) automatically. DO NOT implement your own retry logic on top of the SDK.
- 始终使用SDK。请勿直接通过
ahrefs-python/httpx调用Ahrefs API。requests - 始终以格式的字符串传递日期(例如
YYYY-MM-DD)。"2025-01-15" - 在列表型端点上始终使用参数仅请求所需的列。列表型端点默认返回所有列,这会浪费API额度并增加响应大小。
select - 使用上下文管理器(/
with)管理客户端生命周期。async with - 设置环境变量,而非硬编码API密钥。
AHREFS_API_KEY - 客户端会自动处理重试(429、5xx、连接错误)。请勿在SDK之上自行实现重试逻辑。
Quick Start
快速开始
python
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) # 3python
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) # 3SDK Patterns
SDK使用模式
Client Setup
客户端设置
python
import os
import ahrefs
with ahrefs.AhrefsClient(
api_key=os.environ["AHREFS_API_KEY"],
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:
...Async client:
python
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")python
import os
import ahrefs
with ahrefs.AhrefsClient(
api_key=os.environ["AHREFS_API_KEY"],
base_url="...", # 覆盖API基础URL(默认:https://api.ahrefs.com/v3)
timeout=30.0, # 请求超时时间(秒,默认:60)
max_retries=3, # 临时错误重试次数(默认:2)
) as client:
...异步客户端:
python
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")Calling Methods
调用方法
Two calling styles -- both are equivalent:
python
undefined两种调用方式——功能完全等价:
python
undefinedKeyword arguments (recommended)
关键字参数(推荐)
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
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)
Method names follow `{api_section}_{endpoint}`, e.g. `site_explorer_organic_keywords`, `keywords_explorer_overview`.from ahrefs.types import SiteExplorerDomainRatingRequest
request = SiteExplorerDomainRatingRequest(target="ahrefs.com", date="2025-01-15")
data = client.site_explorer_domain_rating(request)
方法名称遵循`{api模块}_{端点}`的格式,例如`site_explorer_organic_keywords`、`keywords_explorer_overview`。Responses
响应处理
Methods return typed Data objects directly.
Scalar endpoints return a single data object (or ):
Nonepython
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
print(data.domain_rating)List endpoints return a list of data objects. There is no pagination — set to the number of results you need. Use to request only the columns you need:
limitselectpython
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)方法直接返回类型化的数据对象。
标量型端点返回单个数据对象(或):
Nonepython
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
print(data.domain_rating)列表型端点返回数据对象列表。无需分页——设置参数指定所需结果数量。使用参数仅请求所需列:
limitselectpython
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)Error Handling
错误处理
python
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
...All exceptions inherit from .
ahrefs.AhrefsErrorpython
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 包含重试延迟时间
...
except ahrefs.NotFoundError: # 404 资源不存在
...
except ahrefs.APIError as e: # 其他4xx/5xx错误 -- e.status_code、e.response_body 包含错误详情
...
except ahrefs.APIConnectionError: # 网络/超时错误
...所有异常均继承自。
ahrefs.AhrefsErrorCommon Parameters
通用参数
Most list endpoints share these parameters:
| Parameter | Type | Description |
|---|---|---|
| | Domain, URL, or path to analyze |
| | Date in YYYY-MM-DD format |
| | Date range for history endpoints |
| | Two-letter country code (ISO 3166-1 alpha-2) |
| | Comma-separated columns to return |
| | Filter expression |
| | Column and direction, e.g. |
| | Max results to return |
The parameter takes a JSON string. Use to build it:
wherejson.dumps()python
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,
)For full filter syntax (boolean combinators, operators, nested fields), see .
references/filter-syntax.md大多数列表型端点共享以下参数:
| 参数 | 类型 | 描述 |
|---|---|---|
| | 要分析的域名、URL或路径 |
| | 日期,格式为YYYY-MM-DD |
| | 历史数据端点的日期范围 |
| | 两位字母国家代码(ISO 3166-1 alpha-2) |
| | 要返回的列,以逗号分隔 |
| | 过滤表达式 |
| | 排序列和方向,例如 |
| | 要返回的最大结果数 |
wherejson.dumps()python
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.mdAPI Methods
API方法
52 methods across 7 API sections. See for full details.
references/api-methods.md7个API模块下共有52个方法。完整详情请参考。
references/api-methods.md