Build a Keyword Rank Tracker in Python (SQLite + Cron)
Page 2 of Google restarts positions at 1, so a naive tracker logs the wrong rank. Build a Python tracker with the page offset, SQLite history, rank change detection, parallel checks, cron and an email report.
Page 2 of Google results starts counting at position 1 again. If a tracker stores the position field as the rank, a page-2 result at position 3 gets logged as rank 3 instead of 13, and your history quietly lies. I'll build a tracker in Python with the JustSERP API that adds the page offset itself, saves every check to SQLite, flags ups, downs and drop-outs, and runs from cron. It is one file with one dependency, requests.

What you need
- Python 3.9 or newer and
pip install requests. - A JustSERP API key. Sign up and copy the key from your dashboard.
Keep the key in an environment variable and call the API from your own machine or server, never from a browser:
export JUSTSERP_API_KEY="your-key-here"How the tracker works
Every run does the same four things: look up each keyword, find your domain in the results, save today's rank to SQLite, and compare it with the previous run. A rank is a number (1 is the top) or NULL when you are not in the pages checked.

Each request goes to POST https://api.justserp.com/v1/search with the key in the X-API-Key header and keyword in the JSON body. A typical request takes 2 to 4 seconds, which is why the tracker runs keywords in parallel. We always ask Google for unfiltered, non-personalised results, so your own search history cannot skew a check and the list is the full one, without "similar results omitted".
Build the tracker step by step
The pieces below build on each other, so follow them in order.
Step 1: search with retries
Start with a function that finds a keyword's results and retries safely. Errors 400, 401 and 429 mean a bad request, a bad key or no calls left, so retrying does nothing. A 500 means we could not get a usable page even after our own retries, and it is not charged, so another try is free. The client timeout is the part people get wrong: set it to 90 seconds, not 30. A hard query can keep us busy for over a minute, and if your side hangs up first the call is still counted and you lose the answer.
import os
import sqlite3
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import date
from urllib.parse import urlparse
import requests
API_URL = "https://api.justserp.com/v1/search"
API_KEY = os.environ["JUSTSERP_API_KEY"]
DB_PATH = "ranks.db"
DOMAIN = "example.com"
KEYWORDS = ["crm software", "email marketing tool", "invoice app", "seo checker"]
MAX_PAGES = 3 # pages of about 10 results to check per keyword
THREADS = 10 # keep at or below your plan's concurrency
def search(keyword, page=1):
for attempt in range(4):
response = None
try:
response = requests.post(
API_URL,
headers={"X-API-Key": API_KEY},
json={"keyword": keyword, "page": page, "nfpr": "1"},
timeout=90,
)
except requests.RequestException:
pass # network error or timeout: retry below
if response is not None:
if response.status_code == 200:
return response.json()
if response.status_code in (400, 401, 429):
raise RuntimeError(f"{response.status_code}: {response.text}")
time.sleep(2 ** attempt) # 1s, 2s, 4s, 8s
raise RuntimeError(f"Gave up on {keyword!r} page {page}")
Step 2: find your domain
Compare the hostname of every result's link with your domain. The rank is (page - 1) * 10 + position, because position restarts at 1 on each page. That assumes ten organic results per page, which Google does not always give, so treat ranks beyond page 1 as close rather than exact. Also note that page takes over from start when you send both, so send only one. Checking the hostname, not a substring, stops notexample.com from counting as a match. The function stops as soon as it finds you, which also saves API calls.
def host_matches(link, domain):
host = (urlparse(link).hostname or "").removeprefix("www.")
return host == domain or host.endswith("." + domain)
def find_rank(keyword):
for page in range(1, MAX_PAGES + 1):
data = search(keyword, page)
for item in data.get("organic_results") or []:
if host_matches(item["link"], DOMAIN):
return (page - 1) * 10 + item["position"], item["link"]
return None, None
def check(keyword):
try:
rank, url = find_rank(keyword)
return keyword, rank, url, None
except Exception as err: # one bad keyword must not stop the run
return keyword, None, None, str(err)
Step 3: store the history in SQLite
SQLite is a file, needs no server, and ships with Python. One row per keyword per day, with a unique constraint so a second run on the same day replaces the first.
def init_db(conn):
conn.execute("""
CREATE TABLE IF NOT EXISTS ranks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
checked_on TEXT NOT NULL,
keyword TEXT NOT NULL,
domain TEXT NOT NULL,
rank INTEGER,
url TEXT,
UNIQUE (checked_on, keyword, domain)
)
""")
def previous_rank(conn, keyword, today):
return conn.execute(
"""SELECT rank FROM ranks
WHERE keyword = ? AND domain = ? AND checked_on < ?
ORDER BY checked_on DESC LIMIT 1""",
(keyword, DOMAIN, today),
).fetchone() # None means no history yet
def save(conn, today, keyword, rank, url):
conn.execute(
"INSERT OR REPLACE INTO ranks (checked_on, keyword, domain, rank, url) VALUES (?, ?, ?, ?, ?)",
(today, keyword, DOMAIN, rank, url),
)
Only the main thread touches the database. The threads only call the API, which avoids SQLite's rule about sharing a connection between threads.
Step 4: detect rank changes
A change is the previous rank minus the new one: a positive number means you moved up. The NULL cases matter, because "entered the top 30" and "dropped out" are the changes you most want to see.
def describe_change(previous, rank):
if previous is None:
return "new"
prev = previous[0]
if prev is None and rank is None:
return "-"
if prev is None:
return "entered"
if rank is None:
return "dropped out"
diff = prev - rank
if diff > 0:
return f"up {diff}"
if diff < 0:
return f"down {-diff}"
return "same"
Step 5: run in parallel and report
The main function fans the keywords out over a thread pool, saves each answer and prints a report. THREADS = 10 matches the 10 concurrent requests allowed on the Free and Personal plans (25 on Business, 50 on Enterprise). Do not go above your own limit.
def main():
today = date.today().isoformat()
conn = sqlite3.connect(DB_PATH)
init_db(conn)
with ThreadPoolExecutor(THREADS) as pool:
results = list(pool.map(check, KEYWORDS))
lines = [f"Rank report for {DOMAIN} on {today}", ""]
for keyword, rank, url, error in results:
if error:
lines.append(f"{keyword:<30} ERROR {error}")
continue # do not store failed lookups
change = describe_change(previous_rank(conn, keyword, today), rank)
save(conn, today, keyword, rank, url)
lines.append(f"{keyword:<30} {rank if rank else 'not in top ' + str(MAX_PAGES * 10):<14} {change}")
conn.commit()
conn.close()
report = "\n".join(lines)
print(report)
return report
if __name__ == "__main__":
main()
A run prints something like this:
Rank report for example.com on 2026-10-28
crm software 7 up 2
email marketing tool not in top 30 dropped out
invoice app 12 same
seo checker 3 newTo email the report instead of reading it in a log, add this and call send_email(main()). It uses your own SMTP server through environment variables:
import smtplib
from email.message import EmailMessage
def send_email(body):
if not os.environ.get("SMTP_HOST"):
return # email is optional
msg = EmailMessage()
msg["Subject"] = f"Rank report for {DOMAIN}"
msg["From"] = os.environ["SMTP_FROM"]
msg["To"] = os.environ["SMTP_TO"]
msg.set_content(body)
with smtplib.SMTP(os.environ["SMTP_HOST"], 587) as smtp:
smtp.starttls()
smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
smtp.send_message(msg)
Step 6: schedule it with cron
Put the script in a folder such as /opt/rank-tracker, with your secrets in a .env file containing lines like JUSTSERP_API_KEY=.... Restrict it with chmod 600 .env, then run crontab -e and add:
0 7 * * * cd /opt/rank-tracker && set -a && . ./.env && set +a && /usr/bin/python3 tracker.py >> tracker.log 2>&1That runs every day at 07:00 server time. Cron starts with an empty environment, so sourcing .env in the command is what makes the key available. If the script and the report are working in the terminal, they will work from cron too.
To look at a keyword's history at any time, query the file directly:
sqlite3 ranks.db "SELECT checked_on, rank FROM ranks WHERE keyword = 'crm software' ORDER BY checked_on"What it costs in API calls
Each successful (200) request uses one call; 400 and 500 errors are not charged and 401 and 429 never count. With MAX_PAGES = 3 the worst case is 3 calls per keyword per day, so 50 keywords is at most 150 calls a day. A keyword where you rank on page 1 only needs one call because the search stops when it finds you. Lower MAX_PAGES if you only care about the first page.
Habits that keep the history clean
- Run at the same time every day. Rankings move during the day, so a fixed schedule gives clean comparisons.
- Track locally if you serve a city. Add
"location": "Austin,Texas,United States"to the request body, together with a matching"country"such as"United States"(full English name, not a code). The location string is passed to Google as written and not validated, so a typo gives you ordinary non-local results, not an error. See our local SEO tracking guide. - Do not store failures. The script skips errors, so a 429 on one day never looks like "dropped out".
- Back up
ranks.db. It is your history, and a copy of one file is enough. - Keep secrets out of the repo. Add
.envandranks.dbto.gitignore.
Next steps
Create a free account for 2,000 free requests, no credit card needed, and run the tracker on your own keywords today. See the pricing when you need more volume, and read the Python guide for every request parameter.