Article
seomarketing-automationapipythonkeyword-researchtechnical-seobacklink-analysis
Automate SEO Audits with the SEO Analysis Agent
Use the autonomous SEO Analysis Agent to crawl your site, find technical issues, and uncover keyword/backlink opportunities. This guide provides a Python script to launch an audit and retrieve actionable recommendations, streamlining your SEO workflow.
intermediate30 min5 steps
The play
- Set Up Your EnvironmentBefore interacting with the agent, you need to configure your API key. The agent uses an environment variable for authentication. This keeps your key secure and out of your source code. Set the `AHREFS_API_KEY` variable in your terminal.
- Define and Launch the AnalysisCreate a Python script to start the SEO Analysis Agent. You'll send a POST request to the API endpoint, specifying your target domain and the capabilities you want to activate, such as 'site-crawling' and 'technical-seo-audit'.
- Check Job Status and Retrieve ResultsThe agent runs asynchronously. Use the `job_id` from the previous step to poll a status endpoint. Once the status is 'completed', you can fetch the full report from the results endpoint.
- Analyze Prioritized RecommendationsThe results JSON will contain a 'technical_seo_audit' section with prioritized issues (e.g., broken links, slow pages, missing titles). Focus on the 'high-priority' items first, as fixing these provides the most significant SEO impact.
- Identify Keyword and Backlink OpportunitiesReview the 'keyword_research' and 'backlink_analysis' sections of the report. The SEO Analysis Agent identifies high-intent keywords your competitors rank for but you don't. It also surfaces domains linking to multiple competitors, which are prime targets for your own outreach.
Starter code
import requests
import os
import time
import json
# --- Configuration ---
# Set your API key as an environment variable for security
# In your terminal: export AHREFS_API_KEY='your_ahrefs_api_key_here'
API_KEY = os.getenv('AHREFS_API_KEY')
TARGET_DOMAIN = 'your-website.com' # Change this to your domain
# --- Hypothetical API Endpoints ---
BASE_URL = 'https://api.ahrefs.com/v4/seo-analysis-agent'
START_URL = f'{BASE_URL}/start'
STATUS_URL_TPL = f'{BASE_URL}/status/{{job_id}}'
RESULTS_URL_TPL = f'{BASE_URL}/results/{{job_id}}'
def run_seo_analysis_agent(domain):
"""Starts the agent, polls for completion, and returns results."""
if not API_KEY:
print('Error: AHREFS_API_KEY environment variable not set.')
return
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'target_domain': domain,
'capabilities': [
'site-crawling',
'technical-seo-audit',
'keyword-research',
'backlink-analysis',
'rank-tracking'
]
}
# 1. Start the agent
print(f'Starting SEO Analysis Agent for {domain}...')
try:
start_response = requests.post(START_URL, headers=headers, json=payload)
start_response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
except requests.exceptions.RequestException as e:
print(f'API request failed: {e}')
return
if start_response.status_code == 202:
job_id = start_response.json().get('job_id')
print(f'Agent started successfully. Job ID: {job_id}')
else:
print(f'Failed to start agent: {start_response.text}')
return
# 2. Poll for status (in a real-world scenario, use webhooks or a more robust polling strategy)
# This is a simplified example. The following part is a simulation.
print('NOTE: The following is a simulation of a successful API response.')
print('Polling for job completion...')
time.sleep(2) # Simulate waiting
print(f'Status for job {job_id}: completed')
# 3. Fetch results (simulated)
print('Fetching results...')
simulated_results = {
"job_id": job_id,
"target_domain": domain,
"status": "completed",
"technical_seo_audit": {
"high_priority": [
{"issue": "Broken internal links", "count": 42, "url_list": ["/page-a", "/page-b"]},
{"issue": "Pages with slow load time (>3s)", "count": 15, "url_list": ["/slow-page", "/another-one"]}
],
"medium_priority": [{"issue": "Missing meta descriptions", "count": 110}]
},
"keyword_research": {
"opportunities": [
{"keyword": "best seo analysis tools", "intent": "commercial", "your_rank": "--", "competitor_rank": 3},
{"keyword": "how to improve domain rating", "intent": "informational", "your_rank": 25, "competitor_rank": 5}
]
},
"backlink_analysis": {
"gap_opportunities": [
{"linking_domain": "tech-reviews.com", "links_to_competitors": 3, "links_to_you": 0},
{"linking_domain": "marketing-blog.net", "links_to_competitors": 2, "links_to_you": 0}
]
}
}
print('\n--- Analysis Report ---')
print(json.dumps(simulated_results, indent=2))
if __name__ == '__main__':
run_seo_analysis_agent(TARGET_DOMAIN)