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

推荐订阅源

S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
Hacker News: Ask HN
Hacker News: Ask HN
L
Lohrmann on Cybersecurity
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cyber Attacks, Cyber Crime and Cyber Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog
月光博客
月光博客
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Webroot Blog
Webroot Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
F
Full Disclosure
U
Unit 42
Jina AI
Jina AI
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
L
LINUX DO - 最新话题
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
T
Troy Hunt's Blog
腾讯CDC
T
Threatpost
H
Hacker News: Front Page
P
Palo Alto Networks Blog
博客园 - 聂微东
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
Help Net Security
Help Net Security
L
LINUX DO - 热门话题
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Spread Privacy
Spread Privacy

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 to Validate Whether a Project Idea Is Worth Building
Elowen · 2026-05-23 · via DEV Community

You may have an idea: building an AI resume builder, a PDF tool site, a small SaaS product, a content site, an affiliate site, a niche directory, or even a local service website. The first question is simple: is this direction actually worth building?

Many people judge by instinct: this niche seems popular, there seem to be many existing sites, and users probably need it. But before you start building, a more reliable approach is to look at search results. Search results already contain user demand, page types, content formats, and commercial signals.

This article walks through a complete workflow: starting from a project idea, using the TalorData SERP API to collect real search results, turning those results into tables, and then deciding whether the direction has an opportunity.

We will use AI Resume Builder as the example. The same method can also be applied to tool sites, SaaS products, content sites, affiliate sites, directories, and local service websites.

What You Will Get at the End

By following this article, you will produce three tables:

  • Keyword candidate table: turn a project idea into a set of searchable keywords.
  • SERP result table: use the SERP API to check each keyword and collect ranking pages, PAA, ads, domains, and other useful signals.
  • Opportunity decision table: use simple rules to decide which keywords are worth targeting and which ones should be postponed or avoided.

At the end, you should be able to answer three questions:

  • Is there real search demand for this direction?
  • Which sites are already ranking in search results?
  • If I build this now, which keyword or feature should I start with?

Step 1: Turn the Idea into Searchable Keywords

Let's start with a concrete idea: I want to build an AI Resume Builder.

This idea is still too broad. You cannot judge the whole project with only one phrase, because a project usually contains many different user needs. Some users want a free tool. Some want an online resume builder. Some want a cover letter generator. Some only need a resume summary generator.

So the first step is not writing code or calling an API. The first step is turning the idea into search queries that real users might type into Google.

Step 2: Where the Keywords Come From

Keywords should not be guessed randomly. You can get the first batch from several sources.

1. Break Down the Core Features

For an AI Resume Builder, you can start with the core features:

  • Resume generation: ai resume builder
  • Online resume tool: resume builder online
  • Free resume tool: free resume builder
  • Resume summary generation: resume summary generator
  • Cover letter generation: cover letter generator
  • Resume bullet point generation: resume bullet point generator

2. Expand with User Modifiers

When users search for tools, they often add modifiers such as:

  • best, for example best resume builder
  • free, for example free resume builder
  • online, for example resume builder online
  • generator, for example resume summary generator
  • template, for example resume template
  • alternative, for example zety alternative

3. Add Keywords from Search Suggestions and Existing Pages

You can also expand keywords from Google autocomplete, People Also Ask, existing page titles, and discussions on Reddit or Quora.

If you do not know where to start, you can use ChatGPT to generate an initial keyword list, then use a SERP API to verify whether those keywords actually have search results and ranking pages.

Step 3: Create keywords.csv

Put the keywords into a CSV file. Keep the first version simple, with only one column: keyword.

keyword
ai resume builder
resume builder online
free resume builder
resume summary generator
cover letter generator
resume bullet point generator
ai cover letter generator
best resume builder

Enter fullscreen mode Exit fullscreen mode

If you are testing a different project, just replace this column. For example:

  • PDF tool site: pdf compressor online, merge pdf online, pdf to word converter
  • SaaS: email verification API, invoice software, booking software
  • Content site: best dog food for puppies, how to train a puppy
  • Local service site: plumber near me, emergency dentist near me

Step 4: Query Keywords with the TalorData SERP API

Next, send one SERP API request for each keyword. You can register a TalorData account and get an API key with free credits from the official website.

Keep in mind that API requests consume quota. In general, one keyword means at least one request. If you prepare 20 keywords, the test will use around 20 requests. Before expanding the test, start with 5-10 keywords to make sure the workflow works.

The basic TalorData request format looks like this:

curl -X POST 'https://serpapi.talordata.net/serp/v1/request' \
  -H 'Authorization: Bearer YOUR_TALORDATA_API_KEY' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'engine=google' \
  -d 'q=ai resume builder' \
  -d 'json=2'

Enter fullscreen mode Exit fullscreen mode

This request returns Google SERP data for the keyword. For decision-making, we mainly care about these fields:

  • organic results: natural search results, used to see who ranks at the top.
  • People Also Ask: user questions, used to identify content opportunities.
  • ads: advertising results, if available, used to estimate commercial value.
  • titles and URLs: used to understand page types.
  • domains: used to identify and count the sites that appear in search results.

Step 5: Run the Script and Generate the Result Table

The script reads keywords.csv, queries the TalorData SERP API, and outputs two files:

  • serp_opportunities.csv: the analysis table used for judging opportunities.
  • serp_raw_records.jsonl: the raw crawl records, useful for checking how each conclusion was produced.

In the main article, we only show the key part of the code:

TALORDATA_API_KEY = "YOUR_TALORDATA_API_KEY_HERE"
ENDPOINT = "https://serpapi.talordata.net/serp/v1/request"

headers = {
    "Authorization": f"Bearer {TALORDATA_API_KEY}",
    "Content-Type": "application/x-www-form-urlencoded",
    "User-Agent": "curl/8.0.0",
}

data = {
    "engine": "google",
    "q": keyword,
    "json": "2",
}

response = requests.post(ENDPOINT, headers=headers, data=data, timeout=60)
response.raise_for_status()
result = response.json()

Enter fullscreen mode Exit fullscreen mode

This is the part that sends a keyword to TalorData and receives the SERP response. The full script is included at the end of the article.

Step 6: Look at the Result Table Before Judging the Opportunity

The script will produce a table similar to this:

keyword organic_count paa_count ads_present top_domains Initial read
ai resume builder 10 4 true resume.io, resumegenius.com, enhancv.com Demand is clear, but competition is strong
free resume builder 10 5 true canva.com, zety.com, resume.com Strong free-tool demand and obvious commercial competition
resume summary generator 9 6 false tealhq.com, resumeworded.com, kickresume.com Better long-tail opportunity
cover letter generator 10 4 true grammarly.com, resumegenius.com, zety.com Suitable as a feature page entry point

This table is your first project opportunity map. It shows demand strength, ranking-site patterns, and commercial signals behind each keyword.

Step 7: How to Decide Whether a Signal Is Strong or Weak

When judging opportunities, avoid vague words like "many", "few", "strong", or "weak". Use simple rules instead.

Signal How to Judge What It Means
PAA >= 4 Many questions Rich user needs; suitable for content pages or FAQ
PAA 1-3 Some questions Some content opportunity
PAA = 0 Few questions Limited room for content expansion
ads_present = true Ads exist The keyword may have commercial value
Top 10 has 2+ small sites Better new-site opportunity The SERP is not fully dominated by major brands
Top 10 is almost all major sites Strong competition New sites should avoid attacking the core keyword directly

Here, major sites mean strong brands, platforms, or high-authority websites, such as Canva, LinkedIn, Indeed, HubSpot, Forbes, and Wikipedia.

Small sites usually mean niche tool sites, small SaaS products, personal blogs, niche content sites, or emerging product sites.

You should also keep clear "give up" signals. If almost every keyword has a Top 10 dominated by major sites, very few PAA questions, no ads, and no small sites ranking, the direction may have weak demand or may already be heavily monopolized. In that case, do not force the conclusion that it is still worth doing. A better move is to switch to a more specific keyword or choose another direction.

Step 8: Turn the Result into a Conclusion

Now let's go back to the AI Resume Builder example. Based on the sample results, we can make these judgments:

  • ai resume builder: strong demand, but also strong competition. It is not a good first breakthrough keyword.
  • free resume builder: high traffic and commercial value, but many major brands compete for it.
  • resume summary generator: more specific, with many PAA questions, suitable as an early entry point.
  • cover letter generator: clear demand, suitable as a second feature page.

So the direction is not "not worth doing". The real conclusion is: do not start by attacking the hardest core keyword. A more practical starting point is to build specific feature pages first, then expand toward the main tool page.

Step 9: Create Your Opportunity Decision Table

Finally, convert each keyword into a clear decision.

keyword Opportunity Level Suggested Action
ai resume builder Medium Treat it as a long-term target, not the first keyword to attack
free resume builder Medium Has traffic and commercial value, but needs differentiation
resume summary generator High Suitable as one of the first feature pages
cover letter generator High Suitable as a feature expansion page
best resume builder Medium-low Better for later comparison content

The goal is not to produce an absolutely correct answer. The goal is to decide where to put resources first: which pages to build now, which keywords to postpone, and which directions are not worth continuing.

Optional: Turn the Rules into a Simple Score

If you want more automation, you can turn the rules from Step 7 into a simple scoring function. This lets the script output an initial score for each keyword.

def score_keyword(paa_count, ads_present, big_site_count, small_site_count):
    score = 0

    if paa_count >= 4:
        score += 2
    elif paa_count >= 1:
        score += 1

    if ads_present:
        score += 2

    if small_site_count >= 2:
        score += 2

    if big_site_count >= 4:
        score -= 2

    if score >= 4:
        return "High"
    if score >= 2:
        return "Medium"
    return "Low"

Enter fullscreen mode Exit fullscreen mode

This score should not replace human judgment, but it can help you quickly identify which keywords deserve attention first.

Step 10: Apply the Method to Your Own Project

This method can be reused across many project types. You only need to replace the keywords.

Project Type Example Keyword What You Can Validate
Tool site pdf compressor online Tool demand, existing tools, free/paid opportunity
SaaS email verification API Commercial intent, SaaS sites, pricing-page competition
Content site best dog food for puppies Content opportunity, PAA questions, affiliate opportunity
Directory site best AI tools for students Listicle opportunity and existing directory sites
Local service site plumber near me Local competition, local pack, service provider rankings

The general workflow is:

Project idea -> Find keywords -> Query with TalorData SERP API -> Get result table -> Judge opportunity by rules -> Decide whether to build and where to start

Enter fullscreen mode Exit fullscreen mode

Conclusion

A project direction should not be judged only by instinct. You need to look at real search results to understand demand, commercial value, existing ranking sites, and possible entry points.

The value of a SERP API is that it turns Google search results into data you can analyze in batches.

For a new project, the best direction is not always the most popular one. A better direction is one with search demand, commercial value, room for content or feature expansion, and a realistic entry point for a new site.

If you already have an idea, start with 5-10 keywords and run this workflow once. You will have a much clearer view of whether the direction is worth building and where your first step should be.

Full Python script

# -*- coding: utf-8 -*-
import csv
import json
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse

import requests


ROOT = Path(__file__).resolve().parent
ENDPOINT = "https://serpapi.talordata.net/serp/v1/request"
TALORDATA_API_KEY = "YOUR_TALORDATA_API_KEY_HERE"
SERP_PAGE = ""
SERP_NUM = ""


def get_domain(url):
    try:
        return urlparse(url).netloc.replace("www.", "")
    except Exception:
        return ""


def normalize_serp_response(result):
    serp_json = result.get("data", {}).get("json", result)
    if isinstance(serp_json, str):
        return json.loads(serp_json)
    return serp_json


def find_first(data, keys):
    if isinstance(data, dict):
        for key in keys:
            if key in data:
                return data[key]
        for value in data.values():
            found = find_first(value, keys)
            if found is not None:
                return found
    elif isinstance(data, list):
        for item in data:
            found = find_first(item, keys)
            if found is not None:
                return found
    return None


def as_list(value):
    if isinstance(value, list):
        return value
    if isinstance(value, dict):
        return list(value.values())
    return []


def count_any(data, keys):
    value = find_first(data, keys)
    return len(as_list(value))


def fetch_serp(keyword, api_key):
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "curl/8.0.0",
        "Accept": "application/json, text/plain, */*",
    }
    data = {
        "engine": "google",
        "q": keyword,
        "json": "2",
    }
    page = SERP_PAGE.strip()
    num = SERP_NUM.strip()
    if page:
        data["page"] = page
    if num:
        data["num"] = num
    response = requests.post(ENDPOINT, headers=headers, data=data, timeout=60)
    response.raise_for_status()
    return normalize_serp_response(response.json())


def classify_opportunity(paa_count, ads_present, top_domains):
    big_brand_markers = (
        "linkedin.com",
        "indeed.com",
        "canva.com",
        "wikipedia.org",
        "forbes.com",
        "hubspot.com",
    )
    big_site_count = sum(
        1 for domain in top_domains if any(marker in domain for marker in big_brand_markers)
    )
    if paa_count >= 4 and big_site_count <= 2:
        return "High", "Many PAA questions; top results aren’t fully dominated by major sites."
    if ads_present and paa_count >= 3:
        return "Medium", "There is commercial value and some content opportunity."
    if big_site_count >= 4:
        return "Low", "Many major sites in top results; difficult for new sites to enter."
    return "Medium", "Some opportunity; assess further with competitor pages."


def analyze_keyword(keyword, api_key):
    serp = fetch_serp(keyword, api_key)
    organic_results = as_list(
        find_first(serp, ("organic_results", "organic", "organicResults"))
    )
    paa = as_list(
        find_first(serp, ("people_also_ask", "related_questions", "peopleAlsoAsk"))
    )
    ads = as_list(
        find_first(
            serp,
            (
                "ads",
                "paid_results",
                "top_ads",
                "bottom_ads",
                "sponsored_results",
                "sponsored",
                "ad_results",
                "text_ads",
                "shopping_ads",
            ),
        )
    )
    ads_count = len(ads)
    if ads_count == 0:
        ads_count = (
            count_any(serp, ("top_ads",))
            + count_any(serp, ("bottom_ads",))
            + count_any(serp, ("sponsored_results",))
            + count_any(serp, ("sponsored",))
            + count_any(serp, ("ad_results",))
            + count_any(serp, ("text_ads",))
            + count_any(serp, ("shopping_ads",))
        )

    top_domains = []
    for item in organic_results[:10]:
        if not isinstance(item, dict):
            continue
        link = item.get("link") or item.get("url") or item.get("href") or ""
        domain = get_domain(link)
        if domain:
            top_domains.append(domain)

    opportunity_level, recommendation = classify_opportunity(
        len(paa), ads_count > 0, top_domains
    )

    analysis_row = {
        "keyword": keyword,
        "organic_count": len(organic_results),
        "paa_count": len(paa),
        "ads_count": ads_count,
        "ads_present": str(ads_count > 0).lower(),
        "top_domains": ", ".join(top_domains[:5]),
        "opportunity_level": opportunity_level,
        "recommendation": recommendation,
    }
    raw_record = {
        "keyword": keyword,
        "organic_results": organic_results,
        "paa": paa,
        "ads": ads,
        "top_domains": top_domains,
        "full_response": serp,
    }
    return analysis_row, raw_record


def main():
    api_key = TALORDATA_API_KEY.strip()
    if not api_key or api_key == "YOUR_TALORDATA_API_KEY_HERE":
        raise SystemExit(
            "Missing API key. Open analyze_serp_opportunities.py and set TALORDATA_API_KEY."
        )

    keyword_path = ROOT / "keywords.csv"
    output_path = ROOT / "serp_opportunities.csv"
    raw_output_path = ROOT / "serp_raw_records.jsonl"

    with keyword_path.open("r", encoding="utf-8-sig", newline="") as f:
        keywords = [row["keyword"].strip() for row in csv.DictReader(f) if row["keyword"].strip()]

    rows = []
    raw_records = []
    for keyword in keywords:
        print(f"Analyzing: {keyword}")
        row, raw_record = analyze_keyword(keyword, api_key)
        rows.append(row)
        raw_records.append(raw_record)

    fieldnames = [
        "keyword",
        "organic_count",
        "paa_count",
        "ads_count",
        "ads_present",
        "top_domains",
        "opportunity_level",
        "recommendation",
    ]
    try:
        handle = output_path.open("w", encoding="utf-8-sig", newline="")
    except PermissionError:
        stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        output_path = ROOT / f"serp_opportunities_{stamp}.csv"
        handle = output_path.open("w", encoding="utf-8-sig", newline="")
        print(f"serp_opportunities.csv is locked. Writing to {output_path.name} instead.")

    with handle as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    try:
        raw_handle = raw_output_path.open("w", encoding="utf-8")
    except PermissionError:
        stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        raw_output_path = ROOT / f"serp_raw_records_{stamp}.jsonl"
        raw_handle = raw_output_path.open("w", encoding="utf-8")
        print(f"serp_raw_records.jsonl is locked. Writing to {raw_output_path.name} instead.")

    with raw_handle as f:
        for record in raw_records:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")

    print(f"Done: {output_path}")
    print(f"Raw records: {raw_output_path}")


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode