Web Scraping for AI Training: From Crawl to Clean Dataset
Web scraping for AI training turns public web pages into a clean text dataset in six stages: crawl the pages (or start from an archive such as Common Crawl), keep the raw responses as WARC files, extract the main text, filter by language and quality, remove duplicates, and save JSONL records that keep each page's URL, fetch date and robots.txt status. Public datasets are built this way: FineWeb, 15 trillion tokens from 96 Common Crawl snapshots, extracts text with trafilatura, keeps English with a fastText classifier and removes near-copies with MinHash. AI companies also crawl with their own bots, such as OpenAI's GPTBot and Anthropic's ClaudeBot, and RAG apps scrape a narrower set of sources to keep answers current. ProxyField's proxies carry such crawls from $0.29/GB on datacenter IPs and $1.95/GB on residential IPs; start with the Easy Trial: 1 GB for $2.95.
- residential IPs
- 412M+
- from, traffic never expires
- $1.95/GB
- Easy Trial
- 1 GB for $2.95
On this page 9 sections
- The pipeline, from crawl to clean dataset
- robots.txt rules a training crawler must follow (RFC 9309)
- How to collect web data for LLM training: a 7-step pipeline
- RAG web scraping: feeding a retrieval pipeline
- Compliant web scraping for AI training datasets
- Which proxies are best for AI training data?
- Machine learning and NLP web scraping projects
- Sources
- Web Scraping for AI Training FAQ
seed URLs or Common Crawl → crawl (robots.txt, rate limits) → raw WARC → main text → language and quality filters → personal data masked → deduplicated → dataset.jsonl| Use of web data | What you collect | How often | Typical volume |
|---|---|---|---|
| Pretraining a foundation model | Broad web text and code | Large periodic crawls | Billions of pages, often starting from Common Crawl |
| Fine-tuning a model | Domain pages: docs, forums, product data, reviews | Once per dataset version | Thousands to millions of pages |
| RAG (retrieval-augmented generation) | Your sources: docs, knowledge bases, news, competitor pages | Continuously, as pages change | Hundreds to millions of pages |
| Evaluation sets | Pages for test questions and answers | Once, then frozen | Small |
The pipeline, from crawl to clean dataset
| Stage | What happens | Tools and formats | In public pipelines |
|---|---|---|---|
| 1. Source | Crawl the pages yourself, or filter an archive that already has them | Common Crawl: WARC (raw responses), WAT (metadata), WET (plain text), with a URL index | FineWeb starts from 96 Common Crawl snapshots |
| 2. Crawl | A queue of URLs, robots.txt checks, per-site rate limits, retries | Scrapy, Crawlee; robots.txt per RFC 9309 | |
| 3. Store raw | Keep each response before cleaning, so you can re-extract later and audit the source | WARC files | FineWeb extracts from WARC, not WET |
| 4. Extract | Keep the article, docs or post; drop menus, ads, cookie notices and footers | trafilatura | FineWeb uses trafilatura |
| 5. Language | Detect the language and drop pages outside your target | fastText language ID (lid.176) | FineWeb keeps English with a score of 0.65 or more |
| 6. Quality | Drop thin, repetitive and boilerplate pages | Heuristics on length, repeated lines and punctuation (the Gopher and C4 rules) | FineWeb applies both, plus three of its own |
| 7. Personal data | Remove or mask emails, phone numbers and IP addresses | Regular expressions, entity detection | FineWeb masks emails and public IP addresses |
| 8. Deduplicate | Remove exact copies by hash and near-copies by MinHash | hashlib, datasketch, datatrove | FineWeb: MinHash on 5-word shingles, per snapshot |
| 9. Package | Write records with provenance, then tokenize and mix with other sources | JSONL or Parquet shards | Dolma, an open 3-trillion-token corpus, publishes its curation toolkit |
Who crawls for training. OpenAI says GPTBot "is used to crawl content that may be used in training our generative AI foundation models"; Anthropic says ClaudeBot collects "web content that could potentially contribute to their training." Common Crawl's CCBot builds an open archive that "contains petabytes of data, regularly collected since 2008," free to access on Amazon's cloud. Most teams outside the big labs work at the scale of one domain, one language or one product category.
robots.txt rules a training crawler must follow (RFC 9309)
| What the crawler gets | What RFC 9309 says to do |
|---|---|
robots.txt with status 200 | Apply the group for your user agent, or *; the most specific (longest) matching rule wins |
| A redirect | Follow at least five redirects |
| A 4xx status (404, 410 and others) | The file is "unavailable": you may crawl as if there were no rules |
| A 5xx status, or no answer | The file is "unreachable": assume everything is disallowed. After a long outage, such as 30 days, you may use a cached copy or treat the file as unavailable |
| A cached copy | Don't use it for more than 24 hours, unless the file is unreachable |
| A very large file | Parse at least the first 500 KiB |
robots.txt is a request from the site, not access control: the RFC says its rules are "not a form of access authorization." AI opt-outs name bots such as GPTBot or CCBot; for your own crawler, follow the rules for * and any group that names it. Python's built-in urllib.robotparser differs from the RFC in two ways: it applies the first matching rule, not the longest, and its read() treats 401 and 403 as disallow-all. Scrapy's default parser, Protego, follows the longest-match rule. How to read a site's file and terms: how to check if scraping is allowed.
How to collect web data for LLM training: a 7-step pipeline
- Define the dataset. Write down the domains, languages, page types and the size you need. Check whether Common Crawl already has the pages; filtering an archive costs less than crawling.
- Check what each site allows. Read robots.txt as the table above says (cache it for 24 hours at most; a 5xx means stop) and the site's terms, and record any text-and-data-mining reservation.
- Crawl politely. Use a crawler with a queue, retries and per-site rate limits, such as Scrapy or Crawlee. Identify your bot in the user agent, honor
Retry-Afteron a 429 Too Many Requests, and keep the raw responses. - Extract the main content with trafilatura or a similar extractor; keep headings and lists, and store the clean text next to the raw HTML.
- Filter and clean. Detect the language with fastText, drop thin and repetitive pages, and remove or mask personal data such as names, emails and phone numbers.
- Deduplicate and store provenance. Hash each text for exact copies and use MinHash for near-copies. For every record keep the URL, the fetch date, the robots.txt status and any license. In the EU, general-purpose AI model providers must publish a summary of their training content, and provenance makes that possible.
- Refresh and version. Re-crawl on a schedule, keep dataset versions, and record which version trained which model.
Collect (steps 2 to 4 and exact deduplication). It reads robots.txt as RFC 9309 says, through the same proxy as the pages, backs off when a site asks, extracts the main text and writes one JSON line per page:
# pip install requests protego trafilatura
import hashlib, json, os, time
from datetime import datetime, timezone
from urllib.parse import urlsplit
import requests, trafilatura
from protego import Protego
PROXY = os.environ.get("PROXY_URL") # http://<login>-country-us:<password>@gate.proxyfield.io:7000
PROXIES = {"http": PROXY, "https": PROXY} if PROXY else None
UA = "ExampleDatasetBot/1.0 (+https://example.com/bot)"
ROBOTS_TTL = 24 * 3600 # RFC 9309: don't use a cached robots.txt for more than 24 hours
robots = {} # host -> (time fetched, rules)
def robots_rules(url):
host = "{0.scheme}://{0.netloc}".format(urlsplit(url))
cached = robots.get(host)
if cached and time.time() - cached[0] < ROBOTS_TTL:
return cached[1]
try:
r = requests.get(host + "/robots.txt", headers={"User-Agent": UA}, proxies=PROXIES, timeout=30)
if r.status_code == 200:
rules = Protego.parse(r.text) # longest match wins, as RFC 9309 says
elif 400 <= r.status_code < 500:
rules = "allow" # RFC 9309: 4xx means there are no rules
else:
rules = "disallow" # 5xx: assume complete disallow
except requests.RequestException:
rules = "disallow" # unreachable: assume complete disallow
robots[host] = (time.time(), rules)
return rules
def allowed(url):
rules = robots_rules(url)
return rules == "allow" if isinstance(rules, str) else rules.can_fetch(url, UA)
def collect(urls, out="raw.jsonl", delay=2.0):
seen = set()
with open(out, "a", encoding="utf-8") as f:
for url in urls:
if not allowed(url):
continue # the site asks crawlers to stay away: a request, not access control
r = requests.get(url, headers={"User-Agent": UA}, proxies=PROXIES, timeout=30)
if r.status_code in (429, 503):
wait = r.headers.get("Retry-After", "")
time.sleep(int(wait) if wait.isdigit() else 60) # back off as the site asks
continue
if r.status_code != 200:
continue
text = trafilatura.extract(r.text, url=url, include_comments=False)
if not text or len(text.split()) < 50:
continue # empty or thin page
digest = hashlib.sha256(" ".join(text.lower().split()).encode()).hexdigest()
if digest in seen:
continue # exact duplicate
seen.add(digest)
f.write(json.dumps({"id": "sha256:" + digest, "url": url,
"fetched": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"robots": "allowed", "text": text}, ensure_ascii=False) + "\n")
time.sleep(delay)
if __name__ == "__main__":
collect(["https://example.com/docs/page-1", "https://example.com/docs/page-2"])Filter (steps 5 and 6). It labels the language with fastText's lid.176 model, drops near-copies with MinHash and counts what each filter removed:
# pip install fasttext-numpy2-wheel datasketch (model: https://fasttext.cc/docs/en/language-identification.html)
import json
import fasttext
from datasketch import MinHash, MinHashLSH
lid = fasttext.load_model("lid.176.bin")
lsh = MinHashLSH(threshold=0.8, num_perm=128) # pages sharing ~80% of their 5-word shingles count as copies
def minhash(text):
words = text.lower().split()
m = MinHash(num_perm=128)
for i in range(max(1, len(words) - 4)):
m.update(" ".join(words[i:i + 5]).encode())
return m
counts = {"read": 0, "language": 0, "near_duplicate": 0, "kept": 0}
with open("raw.jsonl", encoding="utf-8") as src, open("dataset.jsonl", "w", encoding="utf-8") as out:
for line in src:
rec = json.loads(line)
counts["read"] += 1
labels, probs = lid.predict(rec["text"].replace("\n", " "))
rec["lang"], rec["lang_score"] = labels[0].replace("__label__", ""), round(float(probs[0]), 2)
if rec["lang"] != "en" or rec["lang_score"] < 0.65:
counts["language"] += 1
continue
m = minhash(rec["text"])
if lsh.query(m):
counts["near_duplicate"] += 1
continue
lsh.insert(rec["id"], m)
rec["words"] = len(rec["text"].split())
out.write(json.dumps(rec, ensure_ascii=False) + "\n")
counts["kept"] += 1
print(counts)We ran both scripts on a small test site in October 2026: an English page, a near-copy of it and a German page. The filter printed {'read': 3, 'language': 1, 'near_duplicate': 1, 'kept': 1}, and the kept record looks like this:
{"id": "sha256:98bd61eb…", "url": "https://example.com/docs/page-1", "fetched": "2026-10-27T02:43:37+00:00",
"robots": "allowed", "text": "Title\nThis is paragraph 0 of a long documentation page…",
"lang": "en", "lang_score": 0.91, "words": 145}Log those counts for every run: they are the funnel from pages fetched to pages kept, and they show which filter to tune. The original fasttext package fails on NumPy 2 with ValueError: Unable to avoid copy while creating an array as requested.; fasttext-numpy2-wheel is the same library built for NumPy 2. Add a license field where a site states one.
For millions of pages, move the same logic into Scrapy, which has robots.txt handling, auto-throttling and retries built in (Scrapy tutorial), or into datatrove, the library FineWeb was built with. <login>-country-us in the proxy username asks for a US IP; other targeting goes after it: -region-<region>, -city-<city>, -session-<id> and -ttl-<seconds> (30 to 129,600 seconds, 20 minutes by default), as in <login>-country-us-region-new_york-city-new_york-session-he9f2qga-ttl-600.
RAG web scraping: feeding a retrieval pipeline
Retrieval-augmented generation answers a question by first retrieving relevant passages from your own index, then giving them to the model as context. Web scraping keeps that index current. To scrape websites for a RAG pipeline:
-
Pick the sources
The app should answer from: your docs, a partner's knowledge base, regulators' pages, news sites.
-
Crawl and convert
Each page to clean Markdown, keeping headings, because they make better chunk boundaries.
-
Chunk
The text into passages of a few hundred words, each with the page URL and title.
-
Embed and index
The chunks in a vector or hybrid search index.
-
Re-crawl on change
Compare a hash of each page with the last crawl and re-embed only what changed.
-
Cite the source
Return the URL with each answer, so users can check it and the site gets the visit.
RAG crawls are smaller than training crawls but run all the time, and they often need the same page as seen from different countries, such as local prices or regional regulations, which is where geo-targeted IPs come in.
Compliant web scraping for AI training datasets
A compliant AI dataset rests on the same rules as any scraping, plus three that are specific to AI:
- Text-and-data-mining opt-outs. In the EU, Directive (EU) 2019/790, Article 4, allows text and data mining unless the rightholder has expressly reserved it "in an appropriate manner, such as machine-readable means in the case of content made publicly available online". Honor robots.txt rules and other machine-readable reservations, and keep a record that you did.
- The AI Act's duties for model providers. Under Regulation (EU) 2024/1689, Article 53, providers of general-purpose AI models need a policy to comply with EU copyright law, including those reservations, and must publish a summary of the content used for training, from August 2, 2025.
- Personal data. Public pages still hold personal data, and the GDPR applies to it: filter it before it reaches the dataset. The European Data Protection Board published Guidelines 03/2026 on web scraping in the context of generative AI on July 8, 2026, for public consultation; read the current version, because the text is not final.
- Copyright outside the EU. In the US, courts have decided fair use for AI training case by case.
The full legal picture, with the cases: is AI scraping legal. The general rules for any scraper: is web scraping legal.
Which proxies are best for AI training data?
Start with rotating datacenter proxies and move only the domains that block them to residential proxies. Datacenter IPs cost the least per GB and suit bulk crawls of sites that accept them; residential IPs get through sites that block or challenge datacenter ranges, and give you country, region and city targeting; dedicated ISP IPs fit sources that allowlist your addresses or sessions that must keep one IP for weeks. Proxies spread requests over many IPs and locations; they do not make a crawl lawful or polite. Pacing and the checks above do that.
One job, priced four ways: 1,000,000 pages at 100 KB of HTML each is about 100 GB.
| Option | How it is billed | Cost of the job |
|---|---|---|
| Rotating datacenter proxies | $0.29/GB (1–49 GB), $0.27 (50–249), $0.25 (250–999), $0.22 (1,000+) | 100 GB × $0.27 = $27 |
| Rotating residential proxies | $2.95/GB for 1 GB, $2.79 from 10 GB, $2.49 from 100 GB, $1.95 from 1,000 GB | 100 GB × $2.49 = $249 |
| Mixed: datacenter, residential only for blocking sites | Each product at its own tier | 90 GB × $0.27 + 10 GB × $2.79 = $52.20 |
| Dedicated ISP proxies | Per IP for 30 days: from $2.29, one price for any quantity | 10 IPs × $2.29–$2.79 = $22.90–$27.90 per 30 days; traffic: unlimited; ISP proxies come in the countries their order form lists, which follow stock |
The mixed row assumes a tenth of the traffic needs residential IPs; measure the real share on your targets. The tier rate applies to the whole purchase, and fetching HTML only, without images and scripts, keeps the page size low. Rotating datacenter proxies cover the same countries as residential and are targeted by country only.
What to look for in a proxy for AI data collection:
- Per-GB pricing that suits bursts: no subscription, and traffic that never expires, so a quarterly re-crawl uses what is left from the last one. All purchases are final.
- Location: country, region and city targeting at the same price per GB, for datasets and RAG indexes that should reflect one market.
- Sessions: a new IP on every request for bulk crawls, or a sticky IP from 30 s to 36 h for paginated sources.
- Scale: unlimited concurrent threads, HTTP, HTTPS and SOCKS5 on one gateway,
gate.proxyfield.io:7000, and 412M+ residential IPs in 195+ countries. - Rules you can follow: public pages only, following each site's terms (proxies for web scraping).
Or skip the proxies. For a smaller project, a scraping API can replace running proxies and a crawler's retry logic. ProxyField's Web Scraping API is in development (Contact sales). Its prices are set: $0.50 per 1,000 successful results over plain HTTP, or $0.20 from 10,000 results in one purchase, and $2.00 down to $1.00 per 1,000 with JS rendering. The same 1,000,000 pages would cost $200 over plain HTTP.
Machine learning and NLP web scraping projects
Scraped data suits machine learning when it is cleaned, labeled and documented. Common projects:
- Sentiment and review analysis: product reviews with their star ratings as labels.
- Price prediction: product listings with prices over time.
- Classification: news articles or job ads with their categories.
- NLP corpora: forum threads, documentation or articles in one language or field, for fine-tuning or evaluation.
- Entity extraction: company pages and directories for names, addresses and products.
Each starts with the same crawl-extract-clean steps above; the difference is which fields you keep as labels. More ideas: web scraping projects.
Get started: run your dataset crawl through residential proxies. Start with the Easy Trial: 1 GB for $2.95, no subscription; traffic never expires.
Sources
- Penedo et al., The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale (arXiv 2406.17557, June 2024, revised October 2024)
- Soldaini et al., Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (arXiv 2402.00159)
- RFC 9309, Robots Exclusion Protocol (September 2022)
- Common Crawl, Get started (WARC, WAT and WET files), Overview and CCBot
- OpenAI, Overview of OpenAI Crawlers
- Anthropic Help Center, Does Anthropic crawl data from the web? (updated April 7, 2026)
- fastText, Language identification
- Directive (EU) 2019/790
- AI Act, Regulation (EU) 2024/1689
- EDPB, Guidelines 03/2026 on web scraping in the context of generative AI (July 8, 2026, public consultation)
This is not legal advice. Laws and guidance change; the primary sources above are the authority.
Web Scraping for AI Training FAQ
How does web scraping power AI training?
ProxyField proxies, from $0.29/GB on datacenter IPs and $1.95/GB on residential IPs, carry the kind of crawl that powers AI training: crawlers download public pages, the main text is extracted, filtered, deduplicated and tokenized, and the result becomes part of a model's training mix. A crawl of 1,000,000 pages at 100 KB each moves about 100 GB, which costs $27 on datacenter IPs or $249 on residential IPs. RAG apps scrape a narrower set of sources to keep answers current.
What does a web scraping pipeline for collecting LLM training data look like, from crawling pages to a clean dataset?
Crawl the pages or start from Common Crawl, keep the raw responses as WARC files, extract the main text with a tool such as trafilatura, filter by language (fastText) and quality, mask personal data, remove exact and near-duplicates (hashes and MinHash), and write JSONL records with each page's URL, fetch date and robots.txt status. FineWeb, 15 trillion tokens from 96 Common Crawl snapshots, is a public example of this pipeline.
What proxies are best for collecting web data to train an AI model?
Start with rotating datacenter proxies, which cost the least per GB ($0.29/GB down to $0.22/GB at ProxyField), and send only the domains that block them through residential proxies ($2.95/GB for 1 GB down to $1.95/GB). Use dedicated ISP IPs (from $2.29 per IP for 30 days) for sources that allowlist your addresses. On a 100 GB crawl, that mix can cost about $52 instead of $249 on residential IPs alone.
Does AI use web scraping?
Yes. AI companies run their own crawlers, such as OpenAI's GPTBot and Anthropic's ClaudeBot, to collect content that may be used for training, many datasets start from the Common Crawl archive, and AI assistants fetch pages live to answer questions.
How do AI companies scrape the web?
With named crawlers that follow links across the public web and honor robots.txt rules addressed to them, and by building on open archives such as Common Crawl. Site owners can opt out of a company's training crawler by disallowing its bot, for example GPTBot or ClaudeBot, in robots.txt.
Why is web data important for AI training?
It is the largest and most varied source of text people write: every topic, style and language, plus fresh information that appears after a model's cutoff. For specialized models, the web also holds the forums, documentation and product pages of a single field.
How do I collect web data for LLM training?
Define the domains and size you need, check whether Common Crawl already covers them, then crawl politely: check robots.txt and terms, rate-limit each site, extract the main text, remove duplicates and personal data, and store each page's URL and fetch date with the text. The two Python scripts on this page do the collect and filter steps.
What is web scraping for RAG?
Collecting the pages a retrieval-augmented generation app answers from, such as docs, knowledge bases or news, and keeping them current. The pages are converted to clean text, split into chunks, embedded into a search index and re-crawled when they change, with the source URL kept for citations.
What AI training data can be scraped?
Public pages a site does not reserve against crawling or text and data mining, such as articles, documentation, forums, product listings and reviews. Pages behind logins, content the site has opted out, and personal data without a lawful basis are where the legal risk sits.
What is compliant web scraping for AI training datasets?
Collecting only public pages, honoring robots.txt and other machine-readable text-and-data-mining opt-outs, filtering personal data, pacing requests so sites are not overloaded, and recording the provenance of every page. In the EU, providers of general-purpose AI models must also keep a copyright policy and publish a summary of their training content.
Show 6 more questionsShow fewer questions
Why do AI teams use proxies?
To spread a large crawl over many IP addresses and locations, because sites cap requests per IP, block datacenter ranges, and show different prices, languages and content by country. Proxies do not make a crawl compliant; pacing, robots.txt and data filtering do that.
Do I need proxies to collect LLM training data?
Not if the data is already in an archive such as Common Crawl, or if you collect a few thousand pages slowly from many sites. You do once you fetch tens of thousands of pages from the same sites, need pages as seen from specific countries, or target sites that block datacenter IPs.
Are datacenter proxies good for AI training data?
Yes, for sites that do not block datacenter ranges, because they cost the least per GB of ProxyField's per-GB proxies: its rotating datacenter proxies cost $0.29/GB down to $0.22/GB. Use residential proxies for the sites that block or challenge datacenter IPs.
How do ISP proxies help with AI data pipelines?
They give you fixed IPs that stay yours for weeks, which suits sources that allowlist your IPs and long sessions that must not change address. ProxyField's dedicated ISP proxies cost from $2.29 per IP for a 30-day term, at any quantity.
Is scraped data suitable for machine learning?
Yes, once it is cleaned: remove boilerplate, duplicates and broken records, normalize formats, and keep the labels you need, such as star ratings or categories. Document where each record came from and when, so you can rebuild or audit the dataset.
What are some machine learning web scraping project ideas?
Sentiment analysis on product reviews, price prediction from listings over time, news or job-ad classification, entity extraction from company directories, and domain corpora for fine-tuning a language model.
Related pages
Easy Trial: 1 GB for $2.95.
Try for the price of 1 GB, no subscription, traffic never expires.