Skip to main content
TutorialsNovember 24, 2026 · 13 min read

How to search the web and extract structured data from the results

Turn one search query into validated JSON records: rank and filter results, extract with a schema, de-duplicate, and keep every source URL.

How to search the web and extract structured data from the results

You have a question, not a list of URLs. To search the web and extract JSON from the results, you need to find the right pages, read each one into the same fields, and keep track of where every value came from. This tutorial builds research.py, a pipeline that takes a search query, keeps the results worth reading, extracts one schema from each page with Spidra, de-duplicates the records, and reports search relevance and extraction quality as two separate numbers.

The example question is "how do other guides measure the quality of scraped data?", and the entities are the quality metrics each guide names.

Search for candidate pages

Install the SDK with pip install spidra (Python 3.9 or later) and put your key in SPIDRA_API_KEY. search() waits for the answer. Paging and normalizing the results are covered in How to use a web search API with Python, so this block only runs the query:

# research.py
import json
import os

from spidra import Spidra

from pipeline import extract, merge_metrics, normalize, rank, report

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
QUERY = "web scraping data quality checklist"
found = client.search(QUERY, sources=["web"], limit=10)
for r in found.data.web:
    print(r.position, r.title, "|", r.url)

Choose which results to read before you read any

Every page you read costs credits and seconds, so decide first. Three rules remove most of the waste: skip repeats of the same page, skip sites that rarely hold an article (video, social, Q&A), and keep only results whose title or description mention enough of your query. The first rule needs URLs that compare equal. Result URLs often carry tracking parameters, and normalize() strips them:

# pipeline.py
import re
from datetime import datetime
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

SKIP = {"youtube.com", "reddit.com", "facebook.com", "x.com", "linkedin.com", "stackoverflow.com", "quora.com"}
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "ref", "fbclid", "gclid", "segment_id"}


def normalize(url):
    parts = urlsplit(url.strip())
    query = urlencode(sorted((k, v) for k, v in parse_qsl(parts.query) if k not in TRACKING))
    host = parts.netloc.lower().removeprefix("www.")
    return urlunsplit(("https", host, parts.path.rstrip("/") or "/", query, ""))


def host_of(url):
    return (urlsplit(url).hostname or "").removeprefix("www.")

One of the pages in this run was requested as https://tendem.ai/blog/data-quality-checklist-web-scraping?segment_id=broad:

print(normalize("https://tendem.ai/blog/data-quality-checklist-web-scraping?segment_id=broad"))

Output:

https://tendem.ai/blog/data-quality-checklist-web-scraping

rank() applies the three rules and returns two lists. Every excluded result comes with its reason, so you can see what the filter threw away:

def rank(results, query, keep=5):
    """Split search results into (selected, excluded). Every exclusion carries its reason."""
    terms = [t for t in re.findall(r"[a-z0-9]+", query.lower()) if len(t) > 2]
    need = max(2, len(terms) // 2)
    seen, scored, excluded = set(), [], []
    for r in results:
        host, key = host_of(r.url), normalize(r.url)
        text = f"{r.title} {r.description or ''}".lower()
        hits = sum(t in text for t in terms)
        if key in seen:
            excluded.append((r.url, "same page as an earlier result"))
        elif any(host == d or host.endswith("." + d) for d in SKIP):
            excluded.append((r.url, "video, social or Q&A site"))
        elif hits < need:
            excluded.append((r.url, f"mentions {hits} of the query's {len(terms)} terms"))
        else:
            seen.add(key)
            scored.append((hits, -r.position, r))
    scored.sort(key=lambda s: s[:2], reverse=True)
    selected = [r for _, _, r in scored[:keep]]
    excluded += [(r.url, f"ranked below the top {keep}") for _, _, r in scored[keep:]]
    return selected, excluded

Back in research.py, run it on the results:

selected, excluded = rank(found.data.web, QUERY)
print(len(selected), "selected,", len(excluded), "excluded")
for url, reason in excluded:
    print("  skipped", url, "|", reason)

This filter is a keyword check on titles and descriptions. It can't tell whether a page answers your question, which is why the report at the end measures that separately.

Extract the same fields from every selected page

Batch scrape reads up to 50 URLs in one request, each as its own job with its own result, and a schema makes every page answer in the same shape. A field is nullable when its type includes "null", so a page that doesn't discuss a topic can say so instead of guessing. The prompt tells the extractor to use only what the page says:

# pipeline.py (continued)
def nullable(kind):
    return {"type": [kind, "null"]}


SCHEMA = {
    "type": "object",
    "properties": {
        "metrics": {"type": "array", "items": {"type": "object", "properties": {
            "name": {"type": "string"},
            "definition_or_formula": nullable("string"),
            "states_denominator": nullable("boolean"),
        }}},
        "ground_truth_method": nullable("string"),
        "sample_size_advice": nullable("string"),
        "thresholds": {"type": "array", "items": {"type": "string"}},
        "separates_missing_from_wrong": nullable("string"),
        "separates_valid_from_correct": nullable("string"),
        "plausible_but_wrong_example": nullable("string"),
        "headings": {"type": "array", "items": {"type": "string"}},
        "code_language": nullable("string"),
        "biggest_gaps": nullable("string"),
    },
}

PROMPT = (
    "Analyse this article on measuring web scraping data quality, using only what the page says. "
    "Return: the quality metrics or dimensions it names, each with its formula or definition and whether it states the denominator; "
    "how it says to obtain ground truth or a reference set; any sample size or sampling advice; any numeric thresholds it recommends; "
    "whether it separates a missing value from a wrong value; whether it separates a value that is valid in format from a value that is correct; "
    "any example of a plausible but wrong value; its H2 headings in order; the programming language of its code; and the biggest gaps in the article."
)

extract() sends the selected URLs and sorts the items into records and failures. Each record keeps the URL as it was returned, for citing, and a normalized key, for comparing, so every value can be traced back to a page:

def seconds(item):
    start, end = (datetime.fromisoformat(t.replace("Z", "+00:00")) for t in (item.started_at, item.finished_at))
    return int((end - start).total_seconds())


def extract(client, urls):
    batch = client.batch_scrape(urls, prompt=PROMPT, schema=SCHEMA)
    records, failures = [], []
    for item in batch.items:
        if item.status != "completed":
            failures.append({"url": item.url, "error": item.error})
            continue
        records.append({"source_url": item.url, "key": normalize(item.url), "data": item.result,
                        "problems": validate(item.result), "credits": item.credits_used, "seconds": seconds(item)})
    return records, failures

A batch finishes as completed even when some pages failed, so the loop checks each item's own status.

Validate each record and treat a null as an answer

validate() checks the shape: every key present, lists that are lists, metrics that have names. It never counts a null as a problem, because "this page doesn't say" is the right answer for a page that doesn't say. filled() lists the fields that have a value, which the report uses later:

def validate(data):
    """Shape problems only. A null is a legitimate answer, so it is never a problem here."""
    if not isinstance(data, dict):
        return ["result is not an object"]
    problems = [f"missing key: {key}" for key in SCHEMA["properties"] if key not in data]
    for key in ("headings", "thresholds", "metrics"):
        if key in data and not isinstance(data[key], list):
            problems.append(f"{key} is not a list")
    for metric in data.get("metrics") or []:
        if not isinstance(metric, dict) or not str(metric.get("name") or "").strip():
            problems.append("a metric has no name")
    return problems


def filled(data):
    return [key for key, value in data.items() if value not in (None, "", [])]

For checks on a value itself (absent, null, invalid or inferred), see How to handle missing and null fields in scraped JSON.

De-duplicate entities and keep every source

When two pages name the same metric, you want one entry that lists both pages. merge_metrics() keys each metric on its name, lower-cased and without a trailing parenthetical such as "(Completeness)", and collects the source URLs:

def merge_metrics(records):
    merged = {}
    for record in records:
        for metric in record["data"].get("metrics") or []:
            key = " ".join(re.sub(r"\(.*?\)", "", metric["name"]).lower().split())
            entry = merged.setdefault(key, {"name": metric["name"], "sources": []})
            if record["source_url"] not in entry["sources"]:
                entry["sources"].append(record["source_url"])
    return merged

Measure search relevance and extraction quality separately

A good number on one dimension can hide a bad one. A page can be read perfectly and still be the wrong page, and a page can be the right page and still give you little. report() prints both: how many pages you read answer the question (a judgement you make from the page, passed in as on_topic), and how many schema fields each page filled. Failed pages are listed with their reasons:

def report(records, failures, on_topic):
    """Two separate questions: did search return pages that answer the question, and did extraction fill them?"""
    relevant = [r for r in records if r["key"] in on_topic]
    print(f"search relevance: {len(relevant)} of {len(records)} pages read answer the question")
    for r in records:
        label = "on topic " if r["key"] in on_topic else "off topic"
        print(f"extraction: {len(filled(r['data']))}/{len(SCHEMA['properties'])} fields | {label} | {r['source_url']}")
    for f in failures:
        print("failed:", f["url"], "|", f["error"])

Now run the batch on the selected pages. ON_TOPIC holds the normalized keys of the three pages that are about scraped data:

URLS = [r.url for r in selected]
records, failures = extract(client, URLS)

ON_TOPIC = {
    "https://tendem.ai/blog/data-quality-checklist-web-scraping",
    "https://dev.to/agenthustler/data-quality-in-web-scraping-validation-cleaning-and-deduplication-502k",
    "https://scrapfly.io/blog/posts/how-to-ensure-web-scrapped-data-quality",
}
report(records, failures, ON_TOPIC)

Output:

search relevance: 3 of 4 pages read answer the question
extraction: 9/10 fields | on topic  | https://tendem.ai/blog/data-quality-checklist-web-scraping?segment_id=broad
extraction: 5/10 fields | on topic  | https://dev.to/agenthustler/data-quality-in-web-scraping-validation-cleaning-and-deduplication-502k
extraction: 2/10 fields | on topic  | https://scrapfly.io/blog/posts/how-to-ensure-web-scrapped-data-quality
extraction: 2/10 fields | off topic | https://www.precisely.com/blog/cat-data-quality/how-to-measure-data-quality-effectively-4-proven-strategies/
failed: https://promptcloud20.medium.com/how-to-assess-web-data-quality-a-qa-framework-for-scraped-data-605d16c58969 | Failed to scrape https://promptcloud20.medium.com/how-to-assess-web-data-quality-a-qa-framework-for-scraped-data-605d16c58969: The page was not delivered: the page answered HTTP 403. Nothing was charged. The site refused the visit; retrying with Stealth Mode (useProxy) may help.

The numbers answer different questions:

  • The Precisely page looks like a relevance miss, not an extraction miss. Its headings are about enterprise data quality, such as storage costs and time-to-value, and don't mention scraping. Extraction read it, and the metrics it returned answer a different question. Judge that from the page, not from the fill count.
  • The Scrapfly page is relevant and mostly empty. Its headings are about validation tools, so empty metrics and thresholds are plausible. A low fill rate can mean the page doesn't say, not that extraction failed.
  • The Medium page failed with a 403. The error says why and suggests Stealth Mode. A failed page isn't charged, and re-running that URL with use_proxy=True is the next step.

Neither number measures accuracy. To check that a filled value is right, compare a sample against its source page.

Save the records with their sources

A page that failed leaves no record, and the pages that worked all passed the shape check. This summary covers the cost of the batch, and merged holds the metrics de-duplicated across pages:

print("credits:", sum(r["credits"] for r in records), "| seconds per page:", [r["seconds"] for r in records])
print("shape problems:", sum(len(r["problems"]) for r in records))

Output:

credits: 17 | seconds per page: [29, 13, 7, 29]
shape problems: 0

The batch cost 17 credits for four pages read, and the failed page was free. Now merge the metrics:

merged = merge_metrics(records)
listed = sum(len(r["data"]["metrics"]) for r in records)
print(len(merged), "unique metrics from", listed, "listed")
print(json.dumps(list(merged.values())[0], indent=2))

Output:

24 unique metrics from 24 listed
{
  "name": "Required fields populated (Completeness)",
  "sources": [
    "https://tendem.ai/blog/data-quality-checklist-web-scraping?segment_id=broad"
  ]
}

Nothing merged here, because these four pages use different metric names. Overlap shows up when pages are listicles that cover the same products or companies, and the merge keeps every source for each entity when it does. Last, write the records and the merged metrics to one file, and print the Scrapfly record to see what a mostly empty page looks like:

final = {"query": QUERY,
         "records": [{"source_url": r["source_url"], **r["data"]} for r in records],
         "metrics": list(merged.values())}
with open("research.json", "w", encoding="utf-8") as out:
    json.dump(final, out, indent=2, ensure_ascii=False)
print(json.dumps(final["records"][2], indent=2, ensure_ascii=False))

Output:

{
  "source_url": "https://scrapfly.io/blog/posts/how-to-ensure-web-scrapped-data-quality",
  "biggest_gaps": null,
  "code_language": "python",
  "ground_truth_method": null,
  "headings": [
    "Key Takeaways",
    "Data Quality Challenges",
    "Setup",
    "Soft Validation with Cerberus",
    "Defining Schema",
    "Creating Validation Rules",
    "Real Life Example",
    "Typed Validation with Pydantic",
    "Transforming and Interpreting",
    "Cerberus or Pydantic?",
    "Scraped Data Validation Summary",
    "FAQ"
  ],
  "metrics": [],
  "plausible_but_wrong_example": null,
  "sample_size_advice": null,
  "separates_missing_from_wrong": null,
  "separates_valid_from_correct": null,
  "thresholds": []
}

Test the rules

These tests pin the parts that can quietly go wrong: the exclusion reasons, the null rule and the merge. The search results in them are hand-written for testing:

# test_rules.py
from types import SimpleNamespace as NS

from pipeline import SCHEMA, filled, merge_metrics, rank, validate


def result(position, url, title):
    return NS(position=position, url=url, title=title, description="")


def test_every_exclusion_has_a_reason():
    found = [result(1, "https://www.youtube.com/watch?v=1", "Web scraping data quality checklist"),
             result(2, "https://a.com/guide", "Web scraping data quality checklist"),
             result(3, "https://a.com/guide/?utm_source=x", "Web scraping data quality checklist"),
             result(4, "https://b.com/cooking", "Best pasta recipes")]
    selected, excluded = rank(found, "web scraping data quality checklist")
    assert [r.url for r in selected] == ["https://a.com/guide"]
    assert dict(excluded) == {"https://www.youtube.com/watch?v=1": "video, social or Q&A site",
                              "https://a.com/guide/?utm_source=x": "same page as an earlier result",
                              "https://b.com/cooking": "mentions 0 of the query's 5 terms"}


def test_an_all_null_answer_is_not_a_problem():
    empty = {key: [] if key in ("headings", "thresholds", "metrics") else None for key in SCHEMA["properties"]}
    assert validate(empty) == [] and filled(empty) == []


def test_the_same_metric_from_two_pages_keeps_both_sources():
    pages = [{"source_url": "https://a.com/1", "data": {"metrics": [{"name": "Completeness (Dimension)"}]}},
             {"source_url": "https://b.com/2", "data": {"metrics": [{"name": "completeness"}]}}]
    merged = merge_metrics(pages)
    assert list(merged) == ["completeness"]
    assert merged["completeness"]["sources"] == ["https://a.com/1", "https://b.com/2"]

Run them with pytest -q:

$ pytest -q
...                                                                      [100%]
3 passed in 0.01s

Choose between page content and a schema

Both routes start from a search, and the goal decides which to use:

  • If a model or a person will read the pages, pass scrape_options to Search and each of the top results comes back with its content as Markdown in one call.
  • If you need records you can filter, join and count, search first, pick the pages, then batch scrape them with a schema, as here.
  • If a page type needs clicks or logins before the data appears, use Scrape for that page, because browser actions go on single-page Scrape and not on batch.

What this pipeline doesn't cover

  • The filter checks words in titles and descriptions. It can't judge whether a page answers your question, so keep a human review step for anything that matters.
  • Nothing here measures accuracy. A filled field can still be wrong, so compare a sample against the source pages.
  • Some pages refuse automated visits. A failed page tells you why, and Stealth Mode helps with some.
  • You're reading pages on sites you don't control, so check their terms and robots rules first. Our guide to web scraping and the law is the place to start.

Conclusion

You now have a pipeline that turns a question into cited records: search, filter with reasons, extract one schema, validate, merge, and report relevance and extraction as separate numbers. It's the shape behind research assistants and company-intelligence products: find the sources, read each one into the same fields, merge the entities, and keep every source URL.

Spidra is what keeps each stage short:

  • Search when you don't have the URLs. One call returns titles, links and descriptions for web, news, images, videos, research papers and GitHub, so the pipeline starts from a question.
  • One schema for every page. Batch scrape reads up to 50 URLs per request, gives each page its own result, and returns every field in your schema, with null where a page doesn't say.
  • Failures stay visible and free. A batch finishes even when a page is refused, the failed item says why, and failed pages aren't charged.
  • Fetching is handled. Real browsers, proxies and CAPTCHA solving are included, so you spend your time on rules instead of on getting the page.
  • The rest of the pipeline is in the same account. Map a site, crawl it, parse its PDFs or run a ready-made template, all on one credit balance.

Every plan has every feature, and the dashboard's Code button writes the request for whatever you set up. Create a free account, set SPIDRA_API_KEY, and run research.py with your own question. Change PROMPT and SCHEMA to the entity you care about.

Frequently asked questions

Run a search to get candidate URLs, keep the ones worth reading, then pass them to batch scrape with a JSON schema. Every page comes back in the same shape. Keep each record's source URL so the values stay traceable.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.