Froodl

How to Build a Google Keyword Rank Tracker in Python

Build a Python script that checks where your site ranks on Google for your target keywords. It saves each keyword’s organic position and ranking URL to a CSV, so you can see what moved and which page ranked.

You updated a product page last week. Today, you search for its main keyword and find it in sixth place. Was it tenth before the update? Did a different page from your site rank yesterday? A manual search can show you what’s there now. To answer the other questions, you need a record of what was there before.

In this tutorial, you’ll build a Python script that checks a list of keywords and saves the results to a CSV. It records the highest-ranking organic result from your domain, along with the URL that ranked. That second detail matters when Google starts showing a different page for the same keyword.

Decide What You Want to Track

Start with five to ten keywords tied to pages you care about. If you sell accounting software, for example, you might track “invoice software for freelancers” for a product page and “how to send an invoice” for a guide.

Choose one country for your first run and keep it consistent. If you serve several markets, record each country separately. A position in the US and a position in the UK are two different observations.

This script checks the first page of organic results. If your site doesn’t appear there, it records not_found. Your page could still be ranking further down.

Set up the Script

Install requests and set an environment variable called SCRAPINGDOG_API_KEY with your API key.

python -m pip install requests

The example uses the Scrapingdog Google SERP API to fetch search results as JSON. The script reads organic_results, so ads and other search features stay outside the position count you’re tracking.

Save this as rank_tracker.py. Replace example.com and the sample keywords with your own.

import csv

import os

from datetime import datetime, timezone

from pathlib import Path

from urllib.parse import urlsplit


import requests


API_URL = "https://api.scrapingdog.com/google/"

DOMAIN = "example.com"

COUNTRY = "us"

KEYWORDS = [

    "invoice software for freelancers",

    "invoice tracker for small business",

    "how to send an invoice",

]

OUTPUT = Path("keyword_rankings.csv")


api_key = os.getenv("SCRAPINGDOG_API_KEY")

if not api_key:

    raise SystemExit("Set SCRAPINGDOG_API_KEY before running the script.")


checked_at = datetime.now(timezone.utc).isoformat(timespec="seconds")

write_header = not OUTPUT.exists() or OUTPUT.stat().st_size == 0


with requests.Session() as session, OUTPUT.open(

    "a", newline="", encoding="utf-8"

) as csv_file:

    writer = csv.writer(csv_file)


    if write_header:

        writer.writerow([

            "checked_at_utc", "keyword", "country",

            "position", "ranking_url", "status",

        ])


    for keyword in KEYWORDS:

        position = ""

        ranking_url = ""

        status = "not_found"


        try:

            response = session.get(

                API_URL,

                params={

                    "api_key": api_key,

                    "query": keyword,

                    "country": COUNTRY,

                    "page": 0,

                },

                timeout=30,

            )


            if not response.ok:

                status = f"http_{response.status_code}"

            else:

                results = response.json()["organic_results"]


                for index, result in enumerate(results, start=1):

                    link = result.get("link", "")

                    hostname = urlsplit(link).hostname or ""


                    if hostname == DOMAIN or hostname.endswith(f".{DOMAIN}"):

                        position = index

                        ranking_url = link

                        status = "found"

                        break


        except (requests.RequestException, KeyError, ValueError, TypeError):

            status = "request_or_response_error"


        writer.writerow([

            checked_at, keyword, COUNTRY, position, ranking_url, status,

        ])

        print(f"{keyword}: {position or status}")

Run it with python rank_tracker.py. Each run adds a new set of rows to keyword_rankings.csv, so yesterday’s results stay in the file. An API error gets its own status. That way, a failed request won’t look like your page dropped out of the rankings.

Read the Results Before Changing a Page

Open the CSV in Google Sheets and filter it to one keyword. Compare the position and ranking URL over several days.

Say your pricing page moves from eighth to fifth for “invoice software for freelancers” and stays there for a week. That’s a change worth tracking. If a blog post suddenly replaces the pricing page for the same query, look at what the search results are showing. Google may be surfacing more guides for that keyword, or the two pages may be covering similar ground.

Once you’re happy with the output, schedule the script to run daily with cron or Windows Task Scheduler. Start with the keywords you’d actually make decisions about. A short list you review every week is more useful than a spreadsheet full of rankings you never open.

0 comments

Log in to leave a comment.

Be the first to comment.