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.
· 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 and the transcripts of the YouTube API, and end with a working index you can query.
The pipeline at a glance
Collect URLs. A sitemap, a list of docs pages, the search results for a topic, a channel's uploads.
Fetch and clean. Each page becomes Markdown plus metadata; each video becomes a transcript split into timestamped chunks.
Chunk. Split Markdown by headings, keep transcript chunks as they are.
Embed and store. Any embedding model, any vector store.
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
curl "https://api.scrapecrate.com/v1/web/page?url=https://example.com/blog/hello-world" \
-H "X-API-Key: YOUR_API_KEY"The response holds what a RAG pipeline needs and nothing else:
markdown: the main content of the page, without navigation, footers or scriptstitle, andmetadatawithdescription,canonical_url,language,site_name,author,published_atandimagelinks: every link as{url, text}, handy to crawl a documentation site one level deeperurl,final_url(after redirects),status_code,content_type,rendered,word_countandfetched_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.
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)
raiseThis "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:
curl "https://api.scrapecrate.com/v1/youtube/transcripts/dQw4w9WgXcQ?format=chunks&chunk_size=1000&chunk_overlap=150" \
-H "X-API-Key: YOUR_API_KEY"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.
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
markdownto skip the unchanged ones before embedding.Discover new content. Follow
linksfrom 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
429afterRetry-After.
Beyond pages and videos
The same key reads TikTok captions, 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 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.
Get started
Create a free account: the 100 free credits of each month ingest 50 web pages or 100 video transcripts. The parameters are in the Web Page API reference and the YouTube API reference.
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.