Tutorial 5 min read

LangChain Web Scraping for RAG Data Extraction in 2026

Learn how to use LangChain for web scraping and RAG data extraction, with cleaner ingestion, dynamic-page handling, and fresher context for LLM applications.

(Updated: ) • 859 words

LangChain can store and retrieve a web document without losing where it came from. The useful boundary is between extraction and ingestion: accept the page content first, then attach the source URL, collection time and content hash before splitting it into documents. A vector-store result without that metadata is difficult to check or refresh.

This example uses the current langchain_core Document and in-memory vector-store interfaces. Its default run uses deterministic fake embeddings to check the ingestion path without a paid model call. It does not generate an answer or measure semantic retrieval quality.

Keep extraction separate from document creation

SearchCans Reader accepts a JSON POST to /api/v1/url, with t: "url" and the source URL in s. Read data.markdown only after HTTP and business-code checks. Require a source-specific passage as well: an extracted error page can be nonempty text.

The code was checked with langchain-core==1.6.9. Save it as langchain_ingest.py and run python langchain_ingest.py. The default fixture needs that package but no API key. The LangChain vector-store reference documents the interfaces used here.

import hashlib
import json
import os
from datetime import datetime, timezone
from urllib.request import Request, urlopen
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_core.embeddings import DeterministicFakeEmbedding


def read_markdown(url, required_text, api_key):
    if not isinstance(required_text, str) or not required_text:
        raise ValueError("Choose a source-specific acceptance marker")
    request = Request("https://www.searchcans.com/api/v1/url", method="POST",
                      data=json.dumps({"t": "url", "s": url, "mode": 0,
                                       "proxy": 0}).encode(),
                      headers={"Content-Type": "application/json", "Authorization": "Bearer " + api_key})
    with urlopen(request, timeout=45) as response:
        payload = json.load(response)
    if (not isinstance(payload, dict) or type(payload.get("code")) is not int
            or payload["code"] != 0 or not isinstance(payload.get("data"), dict)):
        raise ValueError("Reader request failed")
    markdown = payload["data"].get("markdown")
    if not isinstance(markdown, str) or required_text not in markdown:
        raise ValueError("Required source content was not extracted")
    return markdown


def documents(url, markdown, checked_at):
    if not isinstance(markdown, str) or not markdown.strip():
        raise ValueError("Empty Markdown must not enter the index")
    digest = hashlib.sha256(markdown.encode()).hexdigest()
    # Paragraph splitting is deliberately small; not a token-size policy.
    parts = [part.strip() for part in markdown.split("\n\n") if part.strip()]
    return [Document(page_content=part,
                     metadata={"source": url, "content_sha256": digest,
                               "checked_at": checked_at, "ordinal": i},
                     id=hashlib.sha256(f"{url}\n{digest}\n{i}".encode()).hexdigest())
            for i, part in enumerate(parts)]


def plumbing_check(docs):
    store = InMemoryVectorStore(embedding=DeterministicFakeEmbedding(size=16))
    store.add_documents(docs)
    hits = store.similarity_search("fixture lookup", k=1)
    assert len(hits) == 1
    assert hits[0].metadata["content_sha256"] == docs[0].metadata["content_sha256"]
    assert hits[0].metadata["source"] == docs[0].metadata["source"]
    return hits


if __name__ == "__main__":
    # No API key or model call is needed for this fixture.
    docs = documents("https://example.org/docs", "First fixture paragraph.\n\nSecond fixture paragraph.",
                     datetime.now(timezone.utc).isoformat())
    hits = plumbing_check(docs)
    print(json.dumps({"chunks": len(docs), "retrieved": len(hits),
                      "source_metadata_retained": True, "semantic_quality_tested": False}))

Switch the input to an accepted live page

url = "https://docs.python.org/3/library/time.html"
markdown = read_markdown(url, "perf_counter", os.environ["SEARCHCANS_API_KEY"])
docs = documents(url, markdown, datetime.now(timezone.utc).isoformat())
# This remains a metadata/plumbing check with fake embeddings.
hits = plumbing_check(docs)

The required marker above is specific to the selected Python documentation page. It is a useful rejection check, not a complete validator: a page containing the marker can still be incomplete, stale or malicious. Keep source-specific assertions for the passages, tables or code the application needs. source records the requested URL; it does not claim that a redirect’s final canonical identity has been verified.

What the local run establishes

The owned two-paragraph fixture produces two Document objects and one retrieved hit. The checks confirm that the source URL and full-document hash survive ingestion and retrieval. Empty Markdown is rejected, changed content gets a different revision hash, and each paragraph keeps its ordinal. Fake embedding vectors do not establish that a question retrieved the most relevant paragraph.

Paragraph splitting keeps this example small. It can leave a very large paragraph or split a code fence, so it is not a production chunking policy. Choose a structure-aware splitter and token budget for the actual corpus, then keep model, splitter and retrieval settings fixed when evaluating labelled questions. Replace fake embeddings with the configured production embedding model before evaluating relevance; do not describe this smoke test as an answer-quality benchmark.

Refresh without mixing revisions

A content hash detects a changed input; it does not delete the old index records. Use the stored source identity and revision when replacing obsolete chunks. The versioning and tombstone example covers that storage transition. The Reader API reference covers rendering and request options when required page content is missing.

LangChain does not remove the need to validate extracted text, review source access or test a retrieval model. There is no setup-time saving, token reduction or hallucination percentage inferred from this example. Its result is narrower: a reproducible ingestion path whose source metadata can be checked.

Tags:

Tutorial Web Scraping Python RAG LLM Integration
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.