Skip to content
site logo mobile

Code Snippets Library >

AI-Powered SEO Analyzer

🔑 ID:

28722

👨‍💻

Python

🕒

22/02/2024
Free

Description:

This is a Python Script that uses my SEO Analyzer API and pairs it with AI’s wonders to create a full analysis for any webpage with SEO-related recommendations which can help you rank better on Google.

Code:

import requests  
import openai  


def call_api(endpoint_url, HTTP_method, api_key=None, params=None):
   
    """ Calls an API endpoint with specified parameters and returns the JSON response.


    Parameters:
    - endpoint_url (str): The URL of the API endpoint.
    - HTTP_method (str): The HTTP method to use ('GET', 'POST').
    - api_key (str, optional): The API key for authentication.
    - params (dict, optional): Parameters to be sent with the request.


    Returns:
    - dict: The JSON response from the API or an error message. """
   


    # Prepare the headers for authentication
    headers = {
        'x-rapidapi-key': api_key,
        'x-rapidapi-host': endpoint_url.split('/')[2]  # Extracts the host from URL
    }
   
    try:
        # Determine the HTTP method and make the request accordingly
        if HTTP_method.upper() == 'GET':
            response = requests.get(endpoint_url, headers=headers, params=params)
        elif HTTP_method.upper() == 'POST':
            response = requests.post(endpoint_url, headers=headers, json=params)
        else:
            return {'error': 'Unsupported method. Please use GET or POST.'}
       
        response.raise_for_status()  # Raises an error for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        return {'error': str(e)}


def openai_generate(user_prompt, selected_model):
    completion = openai.chat.completions.create(
        model=selected_model, messages=[{"role": "user", "content": user_prompt}]
    )
    return completion.choices[0].message.content


#The Prompt we'll use to generate the analysis
prompt = """
###TASK
You are an expert in SEO. Your task is to help me improve my website's SEO, by using a JSON input
I'll provide for you delimited between triple backticks.


###CONTEXT
Make sure you give me insights and analysis for what I can improve based on the below fields:


1. HTTP Fields:
status: Indicates the HTTP status code of the website. A 200 status code means the site is successfully responding, which is good for SEO.
using_https: Shows whether the site is secured with HTTPS. Using HTTPS is a positive ranking signal for search engines.
contentSize: Provides the size of the site's content. It's important for page loading speed, which impacts SEO rankings.
responseTime: The time it takes for the site to respond. Faster response times enhance user experience and can positively impact SEO rankings.



2. title Fields
data, length, words, charPerWord: The title tag's effectiveness is judged by its relevance to the page content,
its length (ideally between 50-60 characters), and its ability to include keywords naturally.



3. meta_description Fields
Similar to the title, the meta description's data, length, words, and charPerWord are important.
An effective meta description should be compelling, within 150-160 characters, and include relevant keywords to improve click-through rates from search results.



4. metadata_info
charset, canonical, viewport: These elements are foundational for SEO, ensuring the site is properly rendered and avoiding duplicate content issues.
robots: Specifies how search engines should index the page, crucial for controlling crawl behavior.
site_image: Having a defined image can enhance shareability and appearance in social media, indirectly benefiting SEO.



5. Page Headings summary
The distribution of headings (H1, H2, H3, etc.) provides structure and hierarchy to the content,
making it easier for search engines to understand the page's main topics and subtopics.



6. word_count
total, Corrected word count, Anchor text words, Anchor Percentage: Content length and the use of anchor texts contribute to SEO by providing context and relevancy.
A higher word count can signal in-depth coverage of a topic, while anchor texts help with internal linking and keyword relevance.



7. links_summary
Total links, External links, Internal: The number and type of links are crucial for SEO. Internal links help distribute page authority throughout the site,
 while external links can provide additional value and credibility.



8. images_analysis
No alt tag: Images without alt tags miss an opportunity for better image optimization.
 Alt tags help search engines understand the content of images, which can contribute to SEO performance.




###INPUT:


JSON: ```[{JSON}]```
"""


# Set the API key for OpenAI
openai.api_key = "YOUR_OPENAI_API_KEY"


#Set the API key for the SEO Analyzer API
API_Key = "YOUR_API_KEY"


#Set the endpoint of the API
API_Endpoint = "https://website-seo-analyzer.p.rapidapi.com/seo/seo-audit-basic"


#Set the URL of the Page
Page_url = "https://learnwithhasan.com"


# Make an API call to a SEO Analyzer API
Json_response = call_api(
    API_Endpoint,
    "GET",
    API_Key,  
    params={"url": Page_url}
)


# Format the final prompt using the JSON response from the API call
final_prompt = prompt.format(JSON=Json_response)


# Generate text using OpenAI's API and the formatted prompt
response = openai_generate(final_prompt, "gpt-3.5-turbo")


# Print the generated response
print(response)

 

Untitled design (82)

GitHub Link

✖️ Not Available

Untitled design (83)

Download File

✖️ Not Available

If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.