К основному содержанию
скилл CX Codex

ahrefs-python — скилл для Claude Code: что делает и как установить

Настраивает агента на работу с библиотекой Ahrefs API на Python. Пригодится при сборе бэклинков, ключевых слов, Domain Rating и запуске аудитов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add OpenClaudia/openclaudia-skills --skill ahrefs-python -a claude-code
npx skills add OpenClaudia/openclaudia-skills --skill ahrefs-research -a claude-code
Открыть на GitHub

Что делает ahrefs-python

Скилл задаёт правила для работы с официальной библиотекой ahrefs-python. В ней реализовано 52 метода для 7 разделов API: Site Explorer, Keywords Explorer, Rank Tracker, Site Audit, Brand Radar, SERP Overview и Batch Analysis. Агент учится вызывать синхронный AhrefsClient или AsyncAhrefsClient, использовать типизированные структуры Pydantic и быстро находить нужные методы через CLI-утилиту python3 -m ahrefs.api_search.

Инструкции запрещают выполнять прямые HTTP-запросы через httpx или requests, так как библиотека сама обрабатывает сетевые сбои и лимиты 429 или 5xx. Для списочных методов скилл строго требует передавать параметр select, чтобы запрашивать только нужные колонки и не тратить лишние кредиты API. Все даты передаются в формате YYYY-MM-DD.

Для работы SDK потребуется Python версии 3.11+ и установленные библиотеки httpx и pydantic. Ключ доступа передаётся через переменную окружения AHREFS_API_KEY.

Какие задачи решает

  • получить метрики Domain Rating и бэклинки через AhrefsClient
  • выгрузить списки органических ключевых слов с фильтрацией по объёму
  • настроить пакетный сбор SEO-метрик для списка доменов
  • сократить расход юнитов API за счёт фильтрации полей в select

Примеры запросов агенту

  • Напиши асинхронный скрипт на ahrefs-python, чтобы получить Domain Rating для домена example.com
  • Найди через ahrefs.search подходящий метод для анализа позиций по ключевым словам
  • Выгрузи топ-10 органических ключей для сайта, ограничив поля через параметр select

Как установить ahrefs-python

1Через Skills CLI (Vercel)

npx skills add OpenClaudia/openclaudia-skills --skill ahrefs-python -a claude-code
npx skills add OpenClaudia/openclaudia-skills --skill ahrefs-research -a claude-code

2Вручную: положить файлы

~/.claude/skills/ahrefs-research/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/ahrefs-research/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о ahrefs-python

Как установить ahrefs-python в Claude Code?

Выполните команду npx skills add OpenClaudia/openclaudia-skills --skill ahrefs-python -a claude-code в терминале.

Что делает скилл ahrefs-python?

Он объясняет агенту синтаксис официального Python SDK для Ahrefs, обучая использовать готовые клиенты, контекстные менеджеры и типизированные модели вместо сырых HTTP-запросов.

Какие зависимости нужны для работы этого SDK?

Необходим Python 3.11+, пакеты httpx и pydantic, а ключ доступа должен лежать в переменной окружения AHREFS_API_KEY.

Исходный текст

SKILL.md · MIT
---
name: ahrefs-python
description: Manages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.
---

# Ahrefs Python SDK Skill

## 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

## Installation

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

Requires Python 3.11+. Dependencies: `httpx`, `pydantic`.

## API Method Discovery

The SDK has 52 methods across 7 API sections. The built-in search tool is the fastest way to find the right method — it returns matching method signatures, parameters, and return types directly, so there's no need to scan through a large reference.

**Python** (preferred when already in a Python context):

```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** (preferred when exploring from the terminal):

```sh
# 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
```

## 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.
- NEVER hardcode API keys in source code. Use the `AHREFS_API_KEY` environment variable or your preferred secrets mechanism.
- The client handles retries (429, 5xx, connection errors) automatically. DO NOT implement your own retry logic on top of the 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
```

## SDK Patterns

### Client Setup

```python
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:
    ...
```

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")
```

For parallel calls, use `asyncio.gather`:

```python
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"),
    )
```

### Calling Methods

Two calling styles -- both are equivalent:

```python
# 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)
```

Method names follow `{api_section}_{endpoint}`, e.g. `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)
```

### 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`.

### Common Parameters

Most list endpoints share these parameters:

| Parameter | Type | Description |
|-----------|------|-------------|
| `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 |

Parameters typed as enums in the API reference (`CountryEnum`, `VolumeModeEnum`, etc.) accept plain strings — pass `country="us"` not `CountryEnum("us")`.

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`.

## API Methods

Use `search_api_methods("query")` or `python3 -m ahrefs.api_search "query"` to find methods by keyword. Search covers all 52 methods across 7 API sections and returns complete signatures, parameters, and response fields.

© OpenClaudia · MIT · OpenClaudia/openclaudia-skills

Похожие скиллы

Всё по теме «SEO и GEO» →
fastapi-python Mindrally Задаёт агенту стиль разработки на FastAPI: async, Pydantic v2, обработка ошибок и структура роутеров. Пригодится, когда пишете API на Python. CX Codex +1 13 900установок python-pro davila7 Скилл для Claude, который ведёт разработку на Python 3.12+: async, типизация, профилирование, uv, ruff, pydantic и FastAPI. 399установок python siviter-xyz Задаёт агенту единый стиль Python: типизация, внедрение зависимостей, структура тестов и модулей. Пригодится, когда правки идут в существующий проект. CX Codex +1 349установок python-fastapi-best-practices-cursorrules-prompt-f PatrickJS Правило Cursor, которое задаёт агенту стиль кода для Python и FastAPI: функциональный подход, Pydantic v2, async-операции. ★ 41 011звёзд репо pydantic-models-py Microsoft Скилл задаёт структуру моделей Pydantic v2 по шаблону из пяти вариантов: Base, Create, Update, Response и InDB. Пригодится, когда нужны схемы запросов и ответов API. 5установок keyword-research aaron-he-zhu Скилл собирает ключевые слова по теме, оценивает частотность и сложность, разбивает на кластеры и выдаёт план контента. CX Codex +1 1 900установок

Из того же набора49

marketing-ideas Скилл с подборкой из 139 маркетинговых приёмов по категориям и подсказками по внедрению. Пригодится, когда нужен мозговой штурм по росту продукта. CX Codex +1 428установок slack-bot Отправляет уведомления и форматированные отчёты в каналы Slack через Webhooks или Bot API. CX Codex +1 424установок linkedin-ads Скилл помогает планировать B2B-кампании в LinkedIn Campaign Manager, собирать аудитории и писать тексты объявлений. Пригодится при настройке таргета и запуске лидогенерации. CX Codex +1 423установок referral-program Инструкция по проектированию реферальных систем и виральных петель. Помогает рассчитать K-фактор, выбрать механику вознаграждений и составить тексты приглашений. CX Codex +1 421установок onboarding-cro Помогает спроектировать онбординг: приветственные экраны, визарды настройки, туры по продукту и чек-листы, которые доводят пользователя до первого результата. CX Codex +1 422установок signup-flow-cro Скилл для аудита и оптимизации воронок регистрации. Помогает сократить отток на формах, настроить социальные логины и сформулировать гипотезы A/B-тестов. CX Codex +1 417установок unsplash-image Ищет стоковые фото на Unsplash, скачивает их и по желанию накладывает заголовок с подзаголовком. Пригодится, когда нужна картинка для статьи или обложки. CX Codex +1 367установок generate-image Скилл генерирует изображения по текстовому описанию через OpenAI или Stability AI. Пригодится, когда агенту нужно подготовить баннер, иконку или иллюстрацию для проекта. CX Codex +1 343установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой