Generative AIby Dhruv Narang

Getting Data from Websites

Our goal now: download data from online websites, and turn it into Documents. LangChain has several web loaders. These are the main three. Start with WebBaseLoader, and use the others only when a page needs them.

LoaderUse it forIt gives
WebBaseLoaderone normal page, or a list of pagesone Document for each address
RecursiveUrlLoadera website: the start page and the pages it links toone Document for each page found
PlaywrightURLLoaderpages that JavaScript buildsone Document for each address

BeautifulSoup: HTML to Plain Text

Definition

BeautifulSoup converts an HTML page into plain text. A web page arrives as HTML, which is code full of tags. We need only the text, so the loader removes the tags with BeautifulSoup.

HTML OF A PAGE<h1>Welcome</h1><p>Hello <b>world</b></p><nav>Home About</nav>get_text()PLAIN TEXTWelcomeHello worldHome About
You import it from bs4:
from bs4 import BeautifulSoup

WebBaseLoader: One Page, or a List of Pages

Definition

WebBaseLoader downloads a web page and gives back its text as a Document, one Document for each address.

The addressa URL, or a list of URLsrequestsdownloads the HTMLbeautifulsoup4gets the text from the HTMLDocumentsone for each address
It reads only the HTML the server sends. Text that JavaScript adds later is missing. The Playwright loader fixes that.
The whole page comes back, so menu words such as Home and Sign in are in the text too. The metadata has the source (the address) and the title.
A real page. We loaded https://example.com.
You look atYou see
len(static_docs)1 (one address gives one Document)
len(static_docs[0].page_content)171 characters. The page is short.
static_docs[0].metadatasource (the address), title ('Example Domain') and language ('en')
Real values from this page. Another page gives other numbers.

RecursiveUrlLoader: A Website and Its Linked Pages

Definition

RecursiveUrlLoader is a crawler. It starts at one page, follows the links on it, and loads every page it reaches. Each page becomes one Document.

start pagepage Apage Bpage A1page A2page B1page B2other site×not followedmax_depth=1: 1 pagemax_depth=2: 3 pagesmax_depth=3: 7 pages
max_depth is how many levels of links to follow. In the picture, max_depth=1 loads only the start page. max_depth=2 also loads the pages it links to. max_depth=3 goes one level further. The code at the end uses 2.
prevent_outside=True keeps the crawler on the same website. The link to another site in the picture is not followed.
extractor decides what text to keep from each page. Without it, each Document is raw HTML, such as <h1>Welcome</h1><p>Hello</p>. With it, you get plain text. In the code it is a one-line function: it takes the page's HTML and returns plain text, using BeautifulSoup.

PlaywrightURLLoader: Pages Built by JavaScript

Definition

PlaywrightURLLoader loads a page with a headless browser: a real web browser that runs in the background, without a screen. The page's JavaScript runs, and then the loader reads the finished page.

The problem: many websites send an empty frame and a JavaScript script. A browser runs the script, and the content appears. WebBaseLoader is not a browser, so it never runs the script and misses the content. Example: on a practice page built this way, it returned only 161 characters and none of the quotes.
What the server sendsan almost empty page+ a JavaScript scriptA headless browserruns the script, whichwrites the content into the pageThe finished pageall the text is thereWebBaseLoader reads thisand misses the contentPlaywrightURLLoaderreads this
remove_selectors deletes the header, footer and nav parts before the text is read.
You do not write JavaScript: the website already has it.
It is costly: the browser runs on your own computer, so it uses your computer's memory (RAM) and processor. Use it only when a simple loader misses the content.

The Code

The code of the three loaders. Pick a tab. Each tab shows what to install first.

install: pip install langchain-community beautifulsoup4langchain-community beautifulsoup4langchain-community playwright unstructured and then run playwright install
from langchain_community.document_loaders import WebBaseLoader

static_loader = WebBaseLoader("https://example.com")
static_docs = static_loader.load()

print(len(static_docs))
print(static_docs[0].metadata)from bs4 import BeautifulSoup
from langchain_community.document_loaders import RecursiveUrlLoader

crawler_loader = RecursiveUrlLoader(
    url="https://docs.python.org/3/tutorial/index.html",
    max_depth=2,
    extractor=lambda html: BeautifulSoup(html, "html.parser").get_text(strip=True),
    prevent_outside=True
)
crawled_docs = crawler_loader.load()

print(len(crawled_docs))from langchain_community.document_loaders import PlaywrightURLLoader

dynamic_loader = PlaywrightURLLoader(
    urls=["https://quotes.toscrape.com/js/"],
    remove_selectors=["header", "footer", "nav"]
)
dynamic_docs = dynamic_loader.load()

print(len(dynamic_docs))
One page gives one Document. A list of addresses gives one Document for each.It starts at one page and follows the links. Every page it reaches is one Document.A headless browser runs the JavaScript of the page first. Then the loader reads the finished page.

Code
Web loaders03_web_loaders.py · 61 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from dotenv import load_dotenv
load_dotenv()

from bs4 import BeautifulSoup
from langchain_community.document_loaders import WebBaseLoader, RecursiveUrlLoader, PlaywrightURLLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter


# ====================================================================
# 1. WebBaseLoader: Static Webpage Loader (Single or List of URLs)
# Requires: pip install beautifulsoup4
# ====================================================================
static_loader = WebBaseLoader("https://ximverse.com")
static_docs = static_loader.load()

print("1. WebBaseLoader Docs Loaded:", len(static_docs))
print("Metadata:", static_docs[0].metadata)


# ====================================================================
# 2. RecursiveUrlLoader: Web Crawler (Crawls sub-links up to max_depth)
# Requires: pip install beautifulsoup4
# ====================================================================
crawler_loader = RecursiveUrlLoader(
    url="https://docs.python.org/3/tutorial/index.html",
    max_depth=2,
    extractor=lambda html: BeautifulSoup(html, "html.parser").get_text(strip=True),
    prevent_outside=True # CRITICAL: Prevents crawler from leaving python.org domain!
)
crawled_docs = crawler_loader.load()

print("2. RecursiveUrlLoader Docs Crawled:", len(crawled_docs))


# ====================================================================
# 3. PlaywrightURLLoader: Headless Browser for Dynamic JavaScript / React
# Requires: pip install playwright && playwright install
# ====================================================================
dynamic_loader = PlaywrightURLLoader(
    urls=["https://quotes.toscrape.com/js/"],
    remove_selectors=["header", "footer", "nav"] # Strip navigation noise
)
dynamic_docs = dynamic_loader.load()

print("3. PlaywrightURLLoader Docs Loaded:", len(dynamic_docs))


# ====================================================================
# 4. Splitting Web Documents into Clean Semantic Chunks
# ====================================================================
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,        # Maximum characters per chunk
    chunk_overlap=50       # 50 characters overlap to preserve context
)

# Takes list[Document] -> Returns smaller list[Document] (Metadata preserved!)
web_chunks = splitter.split_documents(static_docs)

print(f"Total Chunks Created: {len(web_chunks)}")
print("Chunk 1 Metadata (URL & Title Preserved):", web_chunks[0].metadata)
print("Chunk 1 Content Preview:\n", web_chunks[0].page_content[:200])