惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Security @ Cisco Blogs
The Last Watchdog
The Last Watchdog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
aimingoo的专栏
aimingoo的专栏
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
PCI Perspectives
PCI Perspectives
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
B
Blog RSS Feed
小众软件
小众软件
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
Microsoft Azure Blog
Microsoft Azure Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
T
Tor Project blog
A
Arctic Wolf
Jina AI
Jina AI
Hacker News: Ask HN
Hacker News: Ask HN
F
Fortinet All Blogs
Cloudbric
Cloudbric
S
Secure Thoughts
L
LINUX DO - 热门话题
博客园 - 司徒正美
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security Affairs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
P
Privacy International News Feed
AWS News Blog
AWS News Blog
S
Securelist
TaoSecurity Blog
TaoSecurity Blog
AI
AI
O
OpenAI News
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
T
The Blog of Author Tim Ferriss
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
T
Tenable Blog
Last Week in AI
Last Week in AI
WordPress大学
WordPress大学
S
SegmentFault 最新的问题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Use a SERP API with Python to Track Google Rankings
Cecilia Hill · 2026-06-15 · via DEV Community

Tracking Google rankings sounds simple at first.

You have a keyword.

You search it on Google.

You check where your website appears.

That works if you only have one keyword.

But once you need to track 50, 500, or 5,000 keywords across different countries, cities, languages, or devices, manual checking stops making sense.

You need a repeatable workflow.

A simple ranking tracker usually looks like this:

Keyword list → SERP API → organic results → ranking check → CSV/report

In this tutorial, we’ll build a basic Google ranking tracker with Python and a SERP API.

We will:

  1. Load a list of keywords
  2. Send each keyword to a SERP API
  3. Extract Google organic results
  4. Check whether a target domain appears
  5. Save ranking data to a CSV file

This is not a full SEO platform, but it gives you the core logic behind many rank tracking tools.

Why use a SERP API?

You can try to scrape Google directly.

For a small experiment, it may work. But production scraping gets messy quickly.

Google result pages can change by:

  • country
  • city
  • language
  • device
  • search intent
  • query type
  • result features

A single result page may include:

  • organic results
  • ads
  • local packs
  • maps
  • images
  • videos
  • shopping results
  • news results
  • People Also Ask
  • related searches

Then there are the operational issues:

  • blocked requests
  • CAPTCHA
  • proxy management
  • unstable HTML
  • parser maintenance
  • retry logic
  • localization problems

If your real goal is to track rankings, you probably do not want to maintain all of that infrastructure.

A SERP API helps by returning structured search results in JSON.

Instead of parsing raw HTML, you get data like:

{
  "query": "best project management software",
  "organic_results": [
    {
      "position": 1,
      "title": "Best Project Management Software Tools",
      "link": "https://example.com",
      "snippet": "Compare project management tools and pricing..."
    }
  ]
}

That is much easier to work with in Python.

What we are building

Let’s say we want to track whether our target domain appears for several keywords.

Example target domain:

example.com

Example keywords:

best project management software
project management tools
task management app
team collaboration software

For each keyword, we want to collect:

  • keyword
  • target domain
  • ranking position
  • result title
  • result URL
  • snippet
  • whether the domain was found

Example CSV output:

keyword,target_domain,found,position,title,url
best project management software,example.com,yes,3,Example Project Tool,https://example.com
task management app,example.com,no,,, 

Install dependencies

We only need two Python packages:

pip install requests python-dotenv

requests is used to call the SERP API.

python-dotenv is used to load your API key from a .env file.

Create a .env file

Create a file named .env:

SERP_API_KEY=your_api_key_here
SERP_API_URL=https://your-serp-api-endpoint.example.com/search

Do not hardcode API keys directly in your script.

The exact endpoint depends on your SERP API provider. You can use providers such as SerpApi, Serper, SearchAPI, Bright Data, or Talordata. In this tutorial, we’ll use a generic request format so you can adapt it to your provider.

Create a keyword list

Create a file named keywords.txt:

best project management software
project management tools
task management app
team collaboration software

Each line is one keyword.

Basic SERP API request

Create a file named rank_tracker.py.

import os
import requests
from dotenv import load_dotenv


load_dotenv()

SERP_API_KEY = os.getenv("SERP_API_KEY")
SERP_API_URL = os.getenv("SERP_API_URL")


def fetch_google_results(query, location="United States", language="en"):
    if not SERP_API_KEY:
        raise ValueError("Missing SERP_API_KEY environment variable")

    if not SERP_API_URL:
        raise ValueError("Missing SERP_API_URL environment variable")

    params = {
        "api_key": SERP_API_KEY,
        "engine": "google",
        "q": query,
        "location": location,
        "language": language,
        "output": "json",
    }

    response = requests.get(SERP_API_URL, params=params, timeout=30)
    response.raise_for_status()

    return response.json()

Different providers may use different parameter names.

For example:

  • q or query
  • location, gl, or country
  • language, hl, or locale
  • engine, search_type, or type

Check your provider’s documentation and adjust the parameters.

Extract organic results

Most SERP APIs return organic results in a list.

Common response keys include:

  • organic_results
  • organic
  • results

Let’s write a helper function that supports several possible keys.

def get_organic_results(data):
    possible_keys = [
        "organic_results",
        "organic",
        "results",
    ]

    for key in possible_keys:
        value = data.get(key)
        if isinstance(value, list):
            return value

    return []

Now normalize each result.

def normalize_result(item):
    return {
        "position": item.get("position") or item.get("rank"),
        "title": item.get("title") or "",
        "url": item.get("link") or item.get("url") or "",
        "snippet": item.get("snippet") or item.get("description") or "",
    }

This gives us a clean format no matter which provider we use.

Check whether a domain appears

Now we need to check whether the target domain appears in the organic results.

We can use Python’s urllib.parse to extract the domain from each URL.

from urllib.parse import urlparse


def extract_domain(url):
    if not url:
        return ""

    parsed = urlparse(url)
    domain = parsed.netloc.lower()

    if domain.startswith("www."):
        domain = domain[4:]

    return domain

Now write the ranking check function:

def find_domain_ranking(results, target_domain):
    target_domain = target_domain.lower().replace("www.", "")

    for result in results:
        result_domain = extract_domain(result.get("url", ""))

        if result_domain == target_domain or result_domain.endswith("." + target_domain):
            return {
                "found": "yes",
                "position": result.get("position"),
                "title": result.get("title"),
                "url": result.get("url"),
                "snippet": result.get("snippet"),
            }

    return {
        "found": "no",
        "position": "",
        "title": "",
        "url": "",
        "snippet": "",
    }

This checks exact domain matches and subdomains.

For example, it can match:

example.com
blog.example.com
www.example.com

Load keywords from a file

Now let’s read keywords from keywords.txt.

def load_keywords(filename="keywords.txt"):
    with open(filename, "r", encoding="utf-8") as file:
        return [
            line.strip()
            for line in file
            if line.strip()
        ]

Save ranking results to CSV

We can save the final ranking data to a CSV file.

import csv


def save_rankings_to_csv(rows, filename="rankings.csv"):
    fieldnames = [
        "keyword",
        "target_domain",
        "found",
        "position",
        "title",
        "url",
        "snippet",
    ]

    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()

        for row in rows:
            writer.writerow(row)

Full script

Here is the complete version:

import os
import csv
import requests
from urllib.parse import urlparse
from dotenv import load_dotenv


load_dotenv()

SERP_API_KEY = os.getenv("SERP_API_KEY")
SERP_API_URL = os.getenv("SERP_API_URL")


def fetch_google_results(query, location="United States", language="en"):
    if not SERP_API_KEY:
        raise ValueError("Missing SERP_API_KEY environment variable")

    if not SERP_API_URL:
        raise ValueError("Missing SERP_API_URL environment variable")

    params = {
        "api_key": SERP_API_KEY,
        "engine": "google",
        "q": query,
        "location": location,
        "language": language,
        "output": "json",
    }

    response = requests.get(SERP_API_URL, params=params, timeout=30)
    response.raise_for_status()

    return response.json()


def get_organic_results(data):
    possible_keys = [
        "organic_results",
        "organic",
        "results",
    ]

    for key in possible_keys:
        value = data.get(key)
        if isinstance(value, list):
            return value

    return []


def normalize_result(item):
    return {
        "position": item.get("position") or item.get("rank"),
        "title": item.get("title") or "",
        "url": item.get("link") or item.get("url") or "",
        "snippet": item.get("snippet") or item.get("description") or "",
    }


def extract_domain(url):
    if not url:
        return ""

    parsed = urlparse(url)
    domain = parsed.netloc.lower()

    if domain.startswith("www."):
        domain = domain[4:]

    return domain


def find_domain_ranking(results, target_domain):
    target_domain = target_domain.lower().replace("www.", "")

    for result in results:
        result_domain = extract_domain(result.get("url", ""))

        if result_domain == target_domain or result_domain.endswith("." + target_domain):
            return {
                "found": "yes",
                "position": result.get("position"),
                "title": result.get("title"),
                "url": result.get("url"),
                "snippet": result.get("snippet"),
            }

    return {
        "found": "no",
        "position": "",
        "title": "",
        "url": "",
        "snippet": "",
    }


def load_keywords(filename="keywords.txt"):
    with open(filename, "r", encoding="utf-8") as file:
        return [
            line.strip()
            for line in file
            if line.strip()
        ]


def save_rankings_to_csv(rows, filename="rankings.csv"):
    fieldnames = [
        "keyword",
        "target_domain",
        "found",
        "position",
        "title",
        "url",
        "snippet",
    ]

    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()

        for row in rows:
            writer.writerow(row)


def track_rankings(target_domain, keywords, location="United States", language="en"):
    rows = []

    for keyword in keywords:
        print(f"Checking keyword: {keyword}")

        try:
            data = fetch_google_results(
                query=keyword,
                location=location,
                language=language,
            )

            organic_items = get_organic_results(data)
            normalized_results = [
                normalize_result(item)
                for item in organic_items
            ]

            ranking = find_domain_ranking(
                results=normalized_results,
                target_domain=target_domain,
            )

            rows.append({
                "keyword": keyword,
                "target_domain": target_domain,
                "found": ranking["found"],
                "position": ranking["position"],
                "title": ranking["title"],
                "url": ranking["url"],
                "snippet": ranking["snippet"],
            })

        except requests.RequestException as error:
            print(f"Request failed for keyword: {keyword}")
            print(error)

            rows.append({
                "keyword": keyword,
                "target_domain": target_domain,
                "found": "error",
                "position": "",
                "title": "",
                "url": "",
                "snippet": "",
            })

    return rows


if __name__ == "__main__":
    target_domain = "example.com"
    keywords = load_keywords("keywords.txt")

    rankings = track_rankings(
        target_domain=target_domain,
        keywords=keywords,
        location="United States",
        language="en",
    )

    save_rankings_to_csv(rankings, "rankings.csv")

    print("Saved ranking results to rankings.csv")

Run the script:

python rank_tracker.py

You should get a file named:

rankings.csv

Example CSV output

Your CSV may look like this:

keyword,target_domain,found,position,title,url,snippet
best project management software,example.com,yes,4,Example Project Tool,https://example.com,Manage projects and tasks...
project management tools,example.com,no,,,,
task management app,example.com,yes,7,Example Task App,https://example.com/tasks,Task management for teams...

This is the basic ranking tracker.

Track rankings by location

Google results are not the same everywhere.

A keyword may rank differently in:

United States
United Kingdom
Canada
Australia
Singapore

A local keyword may change even more by city.

For example:

best digital marketing agency

could return very different results in New York, London, and Sydney.

You can track multiple locations like this:

locations = [
    "United States",
    "United Kingdom",
    "Singapore",
]

all_rows = []

for location in locations:
    rankings = track_rankings(
        target_domain="example.com",
        keywords=keywords,
        location=location,
        language="en",
    )

    for row in rankings:
        row["location"] = location
        all_rows.append(row)

If you add location, update the CSV fieldnames:

fieldnames = [
    "keyword",
    "location",
    "target_domain",
    "found",
    "position",
    "title",
    "url",
    "snippet",
]

Location is important for:

  • local SEO
  • international SEO
  • agency reporting
  • market research
  • competitor monitoring
  • multi-country search analysis

Track multiple domains

You may also want to track competitors.

Example domains:

example.com
competitor-one.com
competitor-two.com

You can loop through multiple domains:

target_domains = [
    "example.com",
    "competitor-one.com",
    "competitor-two.com",
]

all_rows = []

for domain in target_domains:
    rankings = track_rankings(
        target_domain=domain,
        keywords=keywords,
        location="United States",
        language="en",
    )

    all_rows.extend(rankings)

save_rankings_to_csv(all_rows, "competitor_rankings.csv")

This gives you a basic competitor visibility report.

How to improve this script

This is a simple version, but you can extend it in many ways.

You could add:

  • scheduled daily runs with cron
  • SQLite or Postgres storage
  • ranking history
  • position change detection
  • email alerts
  • Slack notifications
  • competitor domain tracking
  • local city-level tracking
  • dashboard visualization
  • AI-generated SEO summaries

For example, once you store rankings over time, you can detect changes like:

example.com moved from position 8 to position 3 for "project management tools"

That can become the basis for a simple SEO monitoring tool.

Using ranking data with an LLM

SERP data is also useful for AI workflows.

Once you have ranking data, you can ask an LLM to summarize it.

Example prompt:

You are an SEO analyst.

Here is Google ranking data for our domain and competitors.

Summarize:
- which keywords we rank for
- which keywords we are missing
- which competitors appear most often
- what actions we should consider next

You can feed the CSV data or a cleaned summary into the prompt.

This is useful for:

  • SEO copilots
  • weekly ranking summaries
  • competitor analysis
  • content planning
  • market research
  • automated reporting

The key is that the LLM should reason over structured ranking data, not raw search pages.

What to check before choosing a SERP API

Before choosing a SERP API provider, test it with your actual keywords.

Do not only test easy queries.

Try:

brand keywords
commercial keywords
local keywords
long-tail keywords
competitor keywords
high-volume keywords

Then check:

  • Does the API return clean JSON?
  • Are organic results complete?
  • Are positions stable?
  • Are titles, links, and snippets available?
  • Does geo-targeting work correctly?
  • Can you request HTML if needed?
  • Are failed requests billed?
  • How much cleanup does your code need?

Providers such as SerpApi, Serper, SearchAPI, Bright Data, DataForSEO, and Talordata can all be tested for this kind of workflow.

The best choice depends on your use case.

If you only need a few simple Google searches, a lightweight API may be enough.

If you need SEO monitoring, competitor tracking, AI search workflows, or multi-engine SERP data, test the response structure more carefully.

Final thoughts

Tracking Google rankings is not only about checking where a page appears.

It is about building a repeatable search data workflow.

With Python and a SERP API, you can:

  • load keywords
  • collect Google results
  • extract organic rankings
  • check target domains
  • save results to CSV
  • compare rankings across locations
  • monitor competitors
  • feed ranking data into AI workflows

You do not need to build and maintain your own Google scraper to get started.

A SERP API gives you structured search data so you can focus on analysis, reporting, and product logic.

If you want to test this workflow, Talordata is one SERP API worth comparing. It supports structured SERP data, JSON / HTML response formats, geo-targeted results, and search workflows for SEO monitoring, AI agents, competitor tracking, and market research.

Talordata also offers 1,000 free API requests after signup, which is enough to test real keywords before choosing a provider.