ahrefs-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ahrefs Python SDK Skill

Ahrefs Python SDK 技能文档

Overview

概述

The Ahrefs API provides programmatic access to Ahrefs SEO data. The official Python SDK (
ahrefs-python
) provides typed request and response models for all endpoints, auto-generated from the OpenAPI spec.
Key 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(
ahrefs-python
)为所有端点提供了类型化的请求和响应模型,这些模型由OpenAPI规范自动生成。
核心功能:
  • 站点分析工具(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.git
Requires Python 3.11+. Dependencies:
httpx
,
pydantic
.
sh
pip install git+https://github.com/ahrefs/ahrefs-python.git
要求Python 3.11及以上版本。依赖库:
httpx
pydantic

IMPORTANT RULES

重要规则

  • ALWAYS use the
    ahrefs-python
    SDK. DO NOT make raw
    httpx
    /
    requests
    calls to the Ahrefs API.
  • ALWAYS pass dates as strings in
    YYYY-MM-DD
    format (e.g.
    "2025-01-15"
    ).
  • ALWAYS use
    select
    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.
  • USE context managers (
    with
    /
    async with
    ) for client lifecycle management.
  • SET the
    AHREFS_API_KEY
    environment variable rather than hardcoding API keys.
  • The client handles retries (429, 5xx, connection errors) automatically. DO NOT implement your own retry logic on top of the SDK.
  • 始终使用
    ahrefs-python
    SDK。请勿直接通过
    httpx
    /
    requests
    调用Ahrefs API。
  • 始终以
    YYYY-MM-DD
    格式的字符串传递日期(例如
    "2025-01-15"
    )。
  • 在列表型端点上始终使用
    select
    参数仅请求所需的列。列表型端点默认返回所有列,这会浪费API额度并增加响应大小。
  • 使用上下文管理器(
    with
    /
    async with
    )管理客户端生命周期。
  • 设置
    AHREFS_API_KEY
    环境变量,而非硬编码API密钥。
  • 客户端会自动处理重试(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)    # 3
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)    # 3

SDK 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
undefined

Keyword 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
None
):
python
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
limit
to the number of results you need. Use
select
to request only the columns you need:
python
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)
方法直接返回类型化的数据对象。
标量型端点返回单个数据对象(或
None
):
python
data = client.site_explorer_domain_rating(target="ahrefs.com", date="2025-01-15")
print(data.domain_rating)
列表型端点返回数据对象列表。无需分页——设置
limit
参数指定所需结果数量。使用
select
参数仅请求所需列:
python
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.AhrefsError
.
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 包含重试延迟时间
    ...
except ahrefs.NotFoundError:          # 404 资源不存在
    ...
except ahrefs.APIError as e:          # 其他4xx/5xx错误 -- e.status_code、e.response_body 包含错误详情
    ...
except ahrefs.APIConnectionError:     # 网络/超时错误
    ...
所有异常均继承自
ahrefs.AhrefsError

Common Parameters

通用参数

Most list endpoints share these parameters:
ParameterTypeDescription
target
str
Domain, URL, or path to analyze
date
str
Date in YYYY-MM-DD format
date_from
/
date_to
str
Date range for history endpoints
country
str
Two-letter country code (ISO 3166-1 alpha-2)
select
str
Comma-separated columns to return
where
str
Filter expression
order_by
str
Column and direction, e.g.
"volume:desc"
limit
int
Max results to return
The
where
parameter takes a JSON string. Use
json.dumps()
to build it:
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
.
大多数列表型端点共享以下参数:
参数类型描述
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
要返回的最大结果数
where
参数接受JSON字符串。使用
json.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.md

API Methods

API方法

52 methods across 7 API sections. See
references/api-methods.md
for full details.
7个API模块下共有52个方法。完整详情请参考
references/api-methods.md