How to Scrape All Text From a Website With Python
To scrape all text from a website, you need to discover its pages, retrieve their HTML, extract the readable content, remove unwanted elements, and save the results. This guide explains how to scrape text from a website using Python, Beautiful Soup, and Playwright, including how to handle JavaScript-rendered pages and export clean datasets.
Mykolas Juodis
Last updated: Nov 19, 2026
8 min read

TL;DR
- Discover website URLs through XML sitemaps or a crawler, then normalize and deduplicate them before extraction.
- Use Requests and Beautiful Soup for static pages, or Playwright to extract text from JavaScript-rendered websites.
- Remove navigation, scripts, duplicate content, and unnecessary whitespace to produce clean, reusable text.
- Save extracted text as TXT and explore JSON, JSONL, and CSV for structured exports.
Prepare your environment
Before collecting anything, we need a Python environment and a few libraries to handle HTTP requests, HTML parsing, and browser automation.
We'll use Requests to retrieve webpages, Beautiful Soup to extract their content, and Playwright when a website needs JavaScript to display its text.
For larger projects, Scrapy offers built-in crawling, request scheduling, and data-processing features. However, we'll stick with a lightweight Python setup so you can see how each part works.
Set up Python
Install Python 3.9 or later, then create a project directory and virtual environment:
Activate the environment:
Now install the required packages:

Playwright also requires browser binaries. Install Chromium with:
If your operating system doesn't support Playwright's bundled Chromium, you can use a compatible installed Google Chrome browser instead. We'll cover that option in the JavaScript extraction example.
Configure Decodo proxies
Scraping an entire website can mean sending hundreds or thousands of requests to the same server. Depending on the website, this may trigger rate limits, IP-based restrictions, or geographic access controls.
Proxies help manage these challenges by routing requests through intermediary IP addresses. Rotating proxies distribute requests across multiple IPs, reducing the concentration of traffic on a single address.
With Decodo residential proxies, you get access to 115M+ IPs across 195+ locations. You can rotate IP addresses between requests, collect publicly accessible content from different geographic locations, or maintain sticky sessions when a workflow needs a consistent IP.
Here's how to set up your proxies:
- Log in or create an account on the Decodo dashboard.
- Choose Residential proxies and select a subscription that suits your scraping needs, or start with a 3-day free trial.
- Open the Authentication tab to find your generated proxy username and password.
- Go to Proxy setup and select your preferred location, or choose Random.
- Configure your session type. Choose rotating sessions to change IPs between requests or sticky sessions to maintain an IP for a specified duration. We'll use a rotating HTTP(S) connection.
- Generate and copy your proxy endpoint, then keep your authentication credentials available for the next step.
Get residential proxies for scraping text
Unlock superior scraping performance with a free 3-day trial of Decodo's residential proxy network.
Now, let's store those credentials securely rather than hardcoding them into our Python scripts.
Create a file named .env in your project directory and add:
Replace the placeholders with your credentials. The host and port correspond to our rotating residential proxy gateway. If your dashboard generates a different endpoint, use those connection details instead.
Add .env to a .gitignore file to keep your credentials out of version control. Our Python scripts will load them automatically using python-dotenv.
Test your proxy connection
Before collecting website content, let's verify that our proxy is working. Create proxy_test.py and paste the following code:
The script loads our credentials, routes a request through the proxy, and checks the response. Run it with: python proxy_test.py
If successful, you'll receive an HTTP 200 response and information about the proxy IP.

Organize your Python scraping project
Now that our environment and proxies are configured, we can organize the files we'll use to scrape text from the website.
You could write everything in one Python script, but separating URL discovery, text extraction, and data storage makes the code easier to manage and troubleshoot, especially when working with hundreds of pages.
Here's how we'll structure our project:
Each script has a specific job:
- proxy_test.py checks our connection.
- url_discovery.py finds webpages.
- text_extractor.py handles static HTML.
- playwright_extractor.py processes JavaScript-rendered content.
- scrape_website.py combines URL discovery and text extraction across multiple pages.
- The output directory stores our extracted files.
How to find every page on a website
To scrape all text from a website, we first need to discover its URLs. Scraping the homepage alone won't capture articles, documentation, product pages, or other content deeper within the site.
There are two common ways to find these pages: reading the website's XML sitemap or crawling its internal links.
An XML sitemap lists URLs the website makes available to search engines, often at /sitemap.xml or through a location declared in robots.txt.
If no usable sitemap exists, we can crawl the website in Python by following internal links.
Discover pages with Python
We'll use Quotes to Scrape, a website designed for scraping practice. Our script checks for a sitemap, falls back to internal links, and limits discovery to five pages.
Create url_discovery.py and add:
The crawler uses a queue to visit pages, checks robots.txt, and avoids revisiting URLs. It also limits crawl depth and page count to keep the demonstration manageable.
Run with: python url_discovery.py
For a larger crawl, increase the page limit and apply stricter URL normalization. Combining sitemaps and crawling helps discover URLs across a domain, although pagination and dynamically generated links may require additional handling.
Extract the main text from each page
Now that we have our URLs, we can start collecting their content. The extraction method depends on how the website delivers its text.
We'll use Beautiful Soup for pages with text in their initial HTML and Playwright for pages that render content through JavaScript. The same HTML-cleaning principles apply to both.
Extract text with Beautiful Soup
Beautiful Soup is a Python library that parses HTML documents and lets us locate specific elements, remove unwanted content, and extract readable text.
We'll use it alongside Requests to retrieve the HTML version of Frankenstein from Project Gutenberg. The book provides a useful test because it contains a substantial amount of text.
Create text_extractor.py and paste:
The script retrieves HTML through our configured proxy, parses it with Beautiful Soup, and removes common non-content elements. It then collects headings and paragraphs, normalizes whitespace, and saves the text as a UTF-8 file.
Run with: python text_extractor.py
In our test, the request returned HTTP 200 and extracted 75,007 words from Frankenstein. Your output may vary if the source page changes.

Some Project Gutenberg front matter may remain, since get_text() extracts text from the selected HTML rather than automatically identifying the boundaries of the novel.
Extract specific text using CSS selectors
Sometimes we only need particular elements, such as an article headline or its paragraphs. Beautiful Soup's CSS selectors let us target them without collecting the entire page.
Here, select_one() retrieves the first matching headline, while select() collects paragraphs inside the article. The "\n\n" separator preserves readable paragraph breaks.
Selectors depend on the website's structure, so inspect representative pages before processing an entire domain. For more complex layouts, you can also use XPath or CSS selectors to target specific elements.
Handle JavaScript-rendered content with Playwright
Beautiful Soup can only parse the HTML it receives. If a website loads its content through JavaScript after the initial response, Requests may retrieve an incomplete page.
Playwright solves this by running a browser before extraction. We'll demonstrate it using the JavaScript version of Quotes to Scrape.
Create playwright_extractor.py and paste:
The script launches Chromium, waits until the JavaScript-rendered quotes appear, and retrieves the resulting HTML. Beautiful Soup then extracts each quote and its author.
The script uses Playwright's bundled Chromium browser. If you're using an older operating system that doesn't support it, you can add channel="chrome" to the launch configuration to use an installed Google Chrome browser instead.
Run with: python playwright_extractor.py
Our test successfully rendered the page and extracted 10 quotes with their authors.

Waiting for .quote is important because domcontentloaded only confirms that the initial HTML has been parsed. On another website, replace .quote with a selector that identifies the content you need.
When should you use Beautiful Soup or Playwright?
Start with Requests and Beautiful Soup when the HTML already contains the relevant text. They're generally faster and less resource-intensive than browser automation. Use Playwright when JavaScript execution or browser interaction is required.
If you need to process many different websites, decide whether maintaining browser rendering, URL discovery, and cleaning rules is practical for your workload. Managed extraction tools can handle those operations, while a custom Python scraper gives you more control over the implementation.
Combine URL discovery and text extraction
To collect text from multiple pages, we can connect our URL discovery script with Beautiful Soup. Create scrape_website.py in the same project directory:
Run it with: python scrape_website.py
The script discovers URLs, extracts text from each page, and saves the results to a single TXT file. Our existing five-page discovery limit still applies. Increase MAX_PAGES in url_discovery.py to process more pages.
Clean extracted text and remove unnecessary content
Scraping becomes more complicated when the same navigation menus, footers, and promotional elements appear across hundreds of pages. Removing that noise improves the quality of datasets used for analysis, search, and AI applications.
Our earlier examples already demonstrate removing unwanted HTML elements, selecting relevant content, and normalizing whitespace. For larger projects, data cleaning should also include deduplication and checks for incomplete content.
Normalize whitespace and preserve paragraphs
Repeated spaces, tabs, and empty lines can make extracted text difficult to read. We can clean them without removing paragraph boundaries:
The first expression removes unnecessary horizontal whitespace, while the second reduces excessive blank lines.
Preserve meaningful punctuation, URLs, and special characters unless your application specifically requires their removal.
Remove duplicate text
Different URLs can sometimes return identical content. To detect exact duplicates, generate a hash for each cleaned document and track hashes you've already encountered:
Identical text produces the same hash, allowing us to skip repeated documents. For near-duplicates that differ slightly, techniques such as SimHash or MinHash are more suitable.
Export and store extracted text
The right output format depends on what you plan to do with the data. Plain text works for readable archives, JSON preserves metadata, CSV supports spreadsheet analysis, and databases are useful for larger collections.
Plain text output
Our Beautiful Soup example saves the extracted content as a UTF-8-encoded .txt file. This lightweight format works well for text analysis, archiving, and preparing datasets for LLM training or RAG applications.
If preserving headings, lists, and document structure matters, Markdown may be a better choice. You can also scrape a website to Markdown rather than storing everything as plain text.
JSON and CSV output
JSON stores text alongside metadata such as the source URL, title, timestamp, and word count. For instance:
JSONL extends this approach by storing one JSON record per line, making large datasets easier to process incrementally.
CSV is more convenient when you want to analyze pages in Excel or Google Sheets. Each row can represent a webpage, with separate columns for its URL, title, word count, and extracted content. Python's built-in csv module handles quotation marks and embedded newlines.
Database storage for larger projects
For recurring crawls, a database makes it easier to search records, track updates, and avoid duplicate processing. SQLite is a practical option for local projects because it stores data in a single file.
PostgreSQL is useful for structured datasets and concurrent access, while MongoDB can accommodate documents with varying fields.
Avoiding common text-scraping challenges
Even a well-structured scraper can encounter problems once it begins processing different websites or larger numbers of pages.
The most common issues involve failed requests, inconsistent HTML structures, character encoding, and content that changes between visits.
Rate limits and blocked requests
Websites may restrict automated traffic through HTTP 403 responses, rate limits, CAPTCHAs, and other anti-bot systems.
A few HTTP status codes are particularly useful when diagnosing problems:
- 403 Forbidden: The server refuses access to the requested resource.
- 429 Too Many Requests: The website is restricting the request rate.
- 503 Service Unavailable: The server is temporarily unable to process the request.
For temporary failures, exponential backoff helps prevent repeated requests from overwhelming a server. You can also retry failed Python requests using Requests' built-in adapter support.
Inconsistent page structures
A selector that works on one page may fail on another because websites use different content containers. Our Beautiful Soup script already checks <main>, <article>, and [role="main"] before falling back to the body.
For more complex layouts, define additional candidate selectors and test them across representative pages. Avoid assuming that every page on a domain uses the same HTML structure.
Character encoding and text quality
Incorrect character encoding can turn readable text into garbled characters, sometimes called mojibake. Check the encoding of the source response and save extracted files using UTF-8.
Also validate your results before storing them. An HTTP 200 response doesn't guarantee useful content; the page could contain a login screen, CAPTCHA, or incomplete HTML. Tracking extraction lengths, failures, and duplicates helps identify problems before they affect an entire dataset.
Bottom line
Scraping all text from a website requires a reliable way to discover pages, retrieve their content, and separate readable text from unnecessary HTML.
Requests and Beautiful Soup are a practical starting point for static pages, while Playwright handles content that requires JavaScript rendering. Combined with sensible crawling limits, cleaning rules, and structured exports, they provide the foundation for collecting text across an entire website.
Start with a small number of pages, verify the output, and expand the crawl once you're confident that your extraction rules work.
Simplify website text extraction with Decodo
Skip managing browser rendering, proxies, and scraping infrastructure. Let our Web Data API handle data collection while you focus on the results.
About the author

Mykolas Juodis
Head of Marketing
Mykolas is a seasoned digital marketing professional with over a decade of experience, currently leading Marketing department in the web data gathering industry. His extensive background in digital marketing, combined with his deep understanding of proxies and web scraping technologies, allows him to bridge the gap between technical solutions and practical business applications.
Connect with Mykolas via LinkedIn.
All information on Decodo Blog is provided on an as is basis and for informational purposes only. We make no representation and disclaim all liability with respect to your use of any information contained on Decodo Blog or any third-party websites that may belinked therein.


