Web Scraping and Loading Websites for RAG

Fetch pages, crawl a site politely, extract the main content and keep URLs as citations.

Last Updated:

Module 3 · Lesson 3 of 13 · Beginner

Web Scraping and Loading Websites for RAG

Fetch pages, crawl a site politely, extract the main content and keep URLs as citations.

Help centres, documentation sites, product pages and blogs are some of the most common RAG knowledge sources. Getting them into an index means fetching pages, extracting the main content without menus and footers, following links or a sitemap, and keeping each page's URL for citations, all while being a polite visitor. This lesson builds a small, respectful website loader.

What you will learn

  • How to fetch a page and extract its main content as clean text or Markdown
  • How to crawl a site from its sitemap or by following links
  • How to respect robots.txt, rate limits and site terms
  • How to handle JavaScript-rendered pages and changed content

Prerequisites

Scrape responsibly

Only collect content you are allowed to use. Check the site's terms of use and robots.txt, prefer official APIs or exports when they exist, identify your crawler honestly, keep request rates low, and do not collect personal data you have no right to process. For your own organisation's sites, ask the site owners for a sitemap or an export.

Installation

pip install requests beautifulsoup4 trafilatura

Step 1: Fetch one page and extract the main content

Trafilatura is a library that extracts the main text of a web page and discards navigation, ads and boilerplate. It can output Markdown, which keeps headings for structure-aware chunking.

web_loader.py
import time
from dataclasses import dataclass, field
from urllib.parse import urljoin, urldefrag, urlparse
from urllib.robotparser import RobotFileParser

import requests
import trafilatura
from bs4 import BeautifulSoup

USER_AGENT = "ExampleDocsIndexer/1.0 (internal knowledge base; contact: [email protected])"
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT

@dataclass
class Document:
    text: str
    metadata: dict = field(default_factory=dict)

def fetch(url: str, timeout: int = 20) -> str | None:
    response = session.get(url, timeout=timeout)
    if response.status_code != 200 or "text/html" not in response.headers.get("Content-Type", ""):
        return None
    return response.text

def extract(url: str, html: str) -> Document | None:
    text = trafilatura.extract(html, output_format="markdown", include_tables=True, url=url)
    if not text or len(text.split()) < 30:              # skip near-empty pages
        return None
    title = BeautifulSoup(html, "html.parser").title
    return Document(text, {"source": url, "title": title.get_text(strip=True) if title else url})

Replace the contact address in USER_AGENT with a real one so site owners can reach you.

Step 2: Respect robots.txt

def robots_for(base_url: str) -> RobotFileParser:
    parser = RobotFileParser()
    parser.set_url(urljoin(base_url, "/robots.txt"))
    try:
        parser.read()
    except Exception:
        pass                                             # unreachable robots.txt: read() leaves it unset
    return parser

def allowed(robots: RobotFileParser, url: str) -> bool:
    return robots.can_fetch(USER_AGENT, url)

Step 3a: Crawl from a sitemap (preferred)

Most sites publish /sitemap.xml: a list of their pages, often with last-modified dates. It is faster and more polite than following links.

def sitemap_urls(sitemap_url: str) -> list[str]:
    xml = session.get(sitemap_url, timeout=20).text
    soup = BeautifulSoup(xml, "xml")                    # needs: pip install lxml
    if soup.find("sitemapindex"):                       # a sitemap of sitemaps
        return [u for loc in soup.find_all("loc") for u in sitemap_urls(loc.get_text(strip=True))]
    return [loc.get_text(strip=True) for loc in soup.find_all("loc")]

Step 3b: Crawl by following links

When there is no sitemap, follow links within the same site, breadth-first, with a page limit and a delay between requests:

def crawl(start_url: str, max_pages: int = 200, delay: float = 1.0) -> list[Document]:
    site = urlparse(start_url).netloc
    robots = robots_for(start_url)
    queue, seen, docs = [start_url], {start_url}, []
    while queue and len(seen) <= max_pages:
        url = queue.pop(0)
        if not allowed(robots, url):
            continue
        html = fetch(url)
        time.sleep(delay)                               # be polite: one request per second
        if not html:
            continue
        doc = extract(url, html)
        if doc:
            docs.append(doc)
        for a in BeautifulSoup(html, "html.parser").find_all("a", href=True):
            link, _ = urldefrag(urljoin(url, a["href"]))  # absolute URL without #fragment
            if urlparse(link).netloc == site and link not in seen and not link.endswith((".pdf", ".zip", ".jpg", ".png")):
                seen.add(link)
                queue.append(link)
    return docs

docs = crawl("https://docs.example.com/", max_pages=50)
print(len(docs), docs[0].metadata if docs else None)
47 {'source': 'https://docs.example.com/', 'title': 'Example Docs: Getting Started'}

Collect linked PDFs separately and process them with your PDF loader, keeping the PDF URL as the source.

Step 4: Chunk with the URL attached

Because the output is Markdown, split it by headings (Structure-Aware Chunking) and keep the page URL (plus a heading anchor if you can build one) as the citation. Users trust answers more when they can click straight to the source page.

JavaScript-rendered pages

Some sites build their content in the browser with JavaScript; requests then receives an almost empty page. Options, in order of preference: use the site's API or sitemap-provided content, ask the owners for an export, or render pages with a headless browser such as Playwright (pip install playwright, then page.goto(url) and page.content()), which is slower and heavier.

Keeping the index fresh

  • Use sitemap lastmod dates, or HTTP ETag and Last-Modified headers with conditional requests, to fetch only changed pages.
  • Hash the extracted text; re-embed only when the hash changes (Re-Indexing).
  • Remove pages that now return 404 from the index.

Common errors and troubleshooting

  • 403 or 429 responses: you are blocked or rate-limited; slow down, check robots.txt and terms, or ask for access.
  • Extracted text includes menus: try trafilatura's options, or select the main element with BeautifulSoup for that site.
  • Duplicate pages with tracking parameters: normalise URLs (remove query parameters that do not change content).
  • Empty text: the page is JavaScript-rendered; see above.

Key takeaways

  • Extract main content (for example with trafilatura) and keep the URL and title as metadata.
  • Prefer sitemaps over link crawling; limit pages and add delays.
  • Respect robots.txt and terms of use; identify your crawler.
  • Re-crawl incrementally with dates, ETags and content hashes.

Frequently asked questions

Is web scraping legal?

It depends on the site's terms, the content and your jurisdiction. Get permission for anything beyond public, clearly reusable content, and seek legal advice for commercial use.

Can I let an LLM browse instead of indexing?

Agents with web search or fetch tools can read pages at question time (Agentic Research Assistant). Indexing is faster, cheaper and more predictable for a fixed set of sites.

Practice exercises

  1. Index a documentation site of your own organisation from its sitemap and count the chunks per page.
  2. Add conditional requests with the If-Modified-Since header to skip unchanged pages.

Related tutorials