Here are a few examples of how to use the SEMrush API with Python:
Retrieve Domain Analytics
python
from python_semrush.semrush import SemrushClient
# Set your SEMrush API key
api_key = 'your_semrush_api_key'
# Create a SEMrushClient instance
client = SemrushClient(key=api_key)
# Get domain analytics for example.com
domain_analytics = client.domain_analytics(domain='example.com')
# Print the top 5 organic keywords
print("Top 5 Organic Keywords:")
for keyword in domain_analytics.organic_keywords[:5]:
print(f"- {keyword.keyword} (Position: {keyword.position})")
This code demonstrates how to use the `SemrushClient` class to retrieve domain analytics data, including the top organic keywords and their rankings.
Track Keyword Rankings
The SEMrush API supports endpoints for domain analytics and keyword research. You can use the Position Tracking tool to monitor keyword rankings over time, compare against competitors, and identify opportunities like featured snippets[3].
Automate SEO Audits
By leveraging the SEMrush API with Python, you can build custom workflows to automate SEO audits and data extraction. Pipedream is a platform that lets you build workflows and integrations using Python, with built-in support for the SEMrush API[4].
Run Site Audits
The SEMrush API allows you to programmatically run site audits and retrieve the results. Here's an example of how to enable and run a site audit using the API[3]:
python
url = "https://api.semrush.com/management/v1/projects/{ID}/siteaudit/enable"
querystring = {"key":"{API_Key}"}
payload = "{\r\n\t\"domain\": \"amazon.com\",\r\n\t\"scheduleDay\":0,\"notify\":false,\"pageLimit\":1000,\"userAgentType\":1,\"device\":desktop\r\n\t}\r\n\t\r\n"
headers = {'content-type': "application/json", 'cache-control': "no-cache"}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
By integrating the SEMrush API with Python, you can automate various SEO tasks, track keyword rankings, analyze competitor data, and generate comprehensive reports to drive your online marketing strategies.
Citations:[1] https://pypi.org/project/python-semrush/
[2] https://github.com/storerjeremy/python-semrush
[3] https://www.semrush.com/blog/beginners-guide-to-semrush-project-api/
[4] https://pipedream.com/apps/semrush/integrations/python
[5] https://hugoakhtari.com/en/automate-semrush-export-python/