---
title: "Web scraping for LLMs, a RAG pipeline step by step"
description: "Turn web pages into clean Markdown and YouTube videos into timestamped chunks, then embed them for retrieval. A full RAG ingestion pipeline in Python."
url: https://scrapecrate.com/blog/web-scraping-for-llm-rag
markdown: https://scrapecrate.com/blog/web-scraping-for-llm-rag.md
---

# Web scraping for LLMs, from web pages to a RAG index

Turn web pages into clean Markdown and YouTube videos into timestamped chunks, then embed them for retrieval. A full RAG ingestion pipeline in Python.

Published November 27, 2026 · 6 min read

Retrieval-augmented generation (RAG) lives or dies on its data. A model can only answer from what you put in its context, and what you put there is only as good as the text you extracted. Most RAG problems that look like "the model hallucinates" are really ingestion problems: menus and cookie banners inside the chunks, half a table, a transcript with no timestamps to cite.

This guide builds the ingestion side of a RAG system from two very common sources: web pages (documentation, articles, help centers) and YouTube videos (talks, tutorials, product demos). We use two endpoints that are designed for this, the [Web Page to Markdown API](https://scrapecrate.com/url-to-markdown-api.md) and the transcripts of the [YouTube API](https://scrapecrate.com/youtube-api.md), and end with a working index you can query.

## The pipeline at a glance

1. **Collect URLs.** A sitemap, a list of docs pages, the search results for a topic, a channel's uploads.
2. **Fetch and clean.** Each page becomes Markdown plus metadata; each video becomes a transcript split into timestamped chunks.
3. **Chunk.** Split Markdown by headings, keep transcript chunks as they are.
4. **Embed and store.** Any embedding model, any vector store.
5. **Retrieve and cite.** Return the chunk with its source URL (and the timestamp for videos), so answers can link back.

The scraping part, steps 1 and 2, is where most of the engineering time usually goes. Here it is two API calls.

## Web pages to clean Markdown

```bash
curl "https://api.scrapecrate.com/v1/web/page?url=https://example.com/blog/hello-world" \
  -H "X-API-Key: YOUR_API_KEY"
```

```python
# pip install scrapecrate
from scrapecrate import ScrapeCrate

client = ScrapeCrate(api_key="YOUR_API_KEY")
page = client.web.page(url="https://example.com/blog/hello-world")
print(page.data["title"], page.data["word_count"])
print(page.data["markdown"][:500])
```

```javascript
// npm install scrapecrate
import { ScrapeCrate } from 'scrapecrate';

const client = new ScrapeCrate({ apiKey: 'YOUR_API_KEY' });
const page = await client.web.page({ url: 'https://example.com/blog/hello-world' });
console.log(page.data.title, page.data.word_count);
```

The response holds what a RAG pipeline needs and nothing else:

- `markdown`: the main content of the page, without navigation, footers or scripts
- `title`, and `metadata` with `description`, `canonical_url`, `language`, `site_name`, `author`, `published_at` and `image`
- `links`: every link as `{url, text}`, handy to crawl a documentation site one level deeper
- `url`, `final_url` (after redirects), `status_code`, `content_type`, `rendered`, `word_count` and `fetched_at`

Store `metadata.canonical_url` as the source of each chunk rather than the URL you requested: duplicates collapse, and the citations point to the real page. `published_at` and `fetched_at` let you prefer recent content at retrieval time.

Optional flags: `include_text=true` adds the content as plain text (`text`), `include_html=true` adds the raw HTML (`html`) if you want to run your own extraction too.

### Pages that need a browser

Some pages build their content with JavaScript. The plain fetch notices it and answers `400` with the code `render_required` or `empty_page`, unbilled. Retry with `render=true`: the page loads in a headless browser, waits for anti-bot checks and costs 10 credits instead of 2.

```python
from scrapecrate import ApiError

def fetch(url):
    try:
        return client.web.page(url=url)
    except ApiError as err:
        if err.code in ("render_required", "empty_page"):
            return client.web.page(url=url, render=True)
        raise
```

This "plain first, render on demand" pattern keeps the average cost close to 2 credits a page, because most content pages do not need a browser.

## YouTube videos to timestamped chunks

Video is full of knowledge that never makes it into text: conference talks, tutorials, product walkthroughs. The transcript endpoint can cut a video into chunks ready for embeddings with `format=chunks`:

```bash
curl "https://api.scrapecrate.com/v1/youtube/transcripts/dQw4w9WgXcQ?format=chunks&chunk_size=1000&chunk_overlap=150" \
  -H "X-API-Key: YOUR_API_KEY"
```

```python
transcript = client.youtube.transcript(
    video_id="dQw4w9WgXcQ", format="chunks", chunk_size=1000, chunk_overlap=150
)
for chunk in transcript.data["chunks"]:
    print(chunk["index"], chunk["start"], chunk["end"], chunk["text"][:60])
```

```javascript
const transcript = await client.youtube.transcript({
  video_id: 'dQw4w9WgXcQ', format: 'chunks', chunk_size: 1000, chunk_overlap: 150,
});
for (const chunk of transcript.data.chunks) console.log(chunk.index, chunk.start, chunk.end);
```

Each chunk has `index`, `text`, `start` and `end` in seconds. `chunk_size` (200 to 4,000 characters, default 1,000) is the target length; segments are never split, so a chunk never cuts a sentence in half. `chunk_overlap` (0 to 1,000, default 0) repeats whole segments from the end of the previous chunk, so an idea that spans a boundary is still retrievable.

The timestamps are the real win: a retrieved chunk can link to `https://www.youtube.com/watch?v=<id>&t=<start>s`, and the user lands on the exact moment the answer is spoken. Add `lang=en` to get an English track, translated automatically when the video does not have one, which lets you index a multilingual library in one language.

A transcript costs 1 credit, whatever its length.

## Putting it together

Here is a compact ingestion script. It splits Markdown on H2 headings, keeps the transcript chunks, and writes everything to a JSON Lines file that any embedding job can read.

```python
import json
import re

from scrapecrate import ApiError, ScrapeCrate

client = ScrapeCrate()  # reads SCRAPECRATE_API_KEY

PAGES = ["https://example.com/docs/getting-started", "https://example.com/docs/billing"]
VIDEOS = ["dQw4w9WgXcQ"]

def page_chunks(url):
    try:
        page = client.web.page(url=url)
    except ApiError as err:
        if err.code not in ("render_required", "empty_page"):
            raise
        page = client.web.page(url=url, render=True)
    d = page.data
    source = d["metadata"].get("canonical_url") or d["final_url"]
    for i, section in enumerate(re.split(r"\n(?=## )", d["markdown"])):
        if section.strip():
            yield {"id": f"{source}#{i}", "source": source, "title": d["title"], "text": section}

def video_chunks(video_id):
    t = client.youtube.transcript(video_id=video_id, format="chunks", chunk_overlap=150)
    for c in t.data["chunks"]:
        url = f"https://www.youtube.com/watch?v={video_id}&t={int(c['start'])}s"
        yield {"id": f"{video_id}#{c['index']}", "source": url, "title": video_id, "text": c["text"]}

with open("corpus.jsonl", "w", encoding="utf-8") as out:
    for url in PAGES:
        for chunk in page_chunks(url):
            out.write(json.dumps(chunk) + "\n")
    for vid in VIDEOS:
        for chunk in video_chunks(vid):
            out.write(json.dumps(chunk) + "\n")
```

From here, embed `text` with the model of your choice and store the vector with `id`, `source` and `title`. At query time, put the top chunks in the prompt with their `source`, and ask the model to cite it.

Want better titles for the video chunks? One more call to the video metadata endpoint (`/v1/youtube/videos/{video_id}`, 1 credit) returns `title`, `channel_name`, `upload_date` and `description`.

## Keeping the index fresh

- **Re-fetch on a schedule.** Docs change. Re-fetch pages weekly and compare a hash of `markdown` to skip the unchanged ones before embedding.
- **Discover new content.** Follow `links` from an index page to find new docs, or list a channel's latest uploads with the channel videos endpoint.
- **Mind concurrency.** The free plan allows 2 requests in flight, subscriptions more. Use a small worker pool and retry `429` after `Retry-After`.

## Beyond pages and videos

The same key reads [TikTok captions](https://scrapecrate.com/blog/tiktok-transcript-api.md), Reddit threads, reviews and Google results, so you can add community discussions or competitor pages to the corpus without another vendor. If you would rather let an agent fetch content while it answers, the [MCP server guide](https://scrapecrate.com/blog/mcp-server-web-scraping.md) shows how to give Claude or Cursor the same tools. And if you are still choosing a provider, read [how to pick a web scraping API](https://scrapecrate.com/blog/best-web-scraping-api.md).

## Get started

[Create a free account](https://scrapecrate.com/auth/sign-up): the 100 free credits of each month ingest 50 web pages or 100 video transcripts. The parameters are in the [Web Page API reference](https://scrapecrate.com/docs/api/web.md) and the [YouTube API reference](https://scrapecrate.com/docs/api/youtube.md).

## Frequently asked questions

**Why convert web pages to Markdown for an LLM?**

Raw HTML is mostly navigation, scripts and styling, which wastes tokens and confuses retrieval. Markdown keeps the headings, lists, tables and links that carry meaning, so chunks are smaller, cleaner and easier to cite.

**When should I use render=true?**

Only when the plain fetch fails. A page that builds its content with JavaScript answers render_required or empty_page (400, not billed); retry it with render=true, which runs a headless browser and costs 10 credits instead of 2.

**What chunk size should I use for YouTube transcripts?**

Around 1,000 characters (the default) with 100 to 200 characters of overlap works well for most embedding models. Use smaller chunks, 400 to 600, for precise question answering, and bigger ones for summaries.

**How much does it cost to ingest 1,000 pages and 100 videos?**

1,000 plain web pages cost 2,000 credits and 100 transcripts cost 100 credits, about $2.10 at the list price, before embedding costs. Pages that need rendering cost 10 credits each. Failed calls are never billed.

**Can an agent fetch pages on demand instead of a pipeline?**

Yes. The same endpoints are tools of the ScrapeCrate MCP server, so an agent can call web_page or youtube_transcript while it answers. Use a pipeline for a stable knowledge base and the MCP tools for fresh, one-off lookups.

## Try it with free credits every month

One API key for every source in this guide. No card needed, and only successful calls are billed.

[Create a free account](https://scrapecrate.com/auth/sign-up) [Read the docs](https://scrapecrate.com/docs.md)

## Related guides

- [An MCP server for web scraping, set up in five minutes Give Claude, Cursor or any MCP client live web data: YouTube, Google Maps, reviews, ads, Reddit and web pages through one MCP server, local or remote.](https://scrapecrate.com/blog/mcp-server-web-scraping.md)
- [How to choose the best web scraping API What makes a web scraping API good in 2026, how per-request, credit, bandwidth and compute pricing compare, and when one API for every source wins.](https://scrapecrate.com/blog/best-web-scraping-api.md)
- [TikTok transcript API, captions and comments in one call Get the transcript of any public TikTok video as text, JSON segments, SRT or VTT, plus its stats and comments. Code in curl, Python and JavaScript.](https://scrapecrate.com/blog/tiktok-transcript-api.md)

[← All guides](https://scrapecrate.com/blog.md)
