"Claude Code struggles with web scraping" is one of the more common complaints in the developer subreddits, and it usually bundles two different problems. One is mechanical: Claude Code's built-in page tool wasn't designed to extract data in bulk. The other is behavioral: some scraper requests get declined. Both are manageable once you know which one you hit.
This post is about using Claude Code as the developer who writes and checks the scraper. If you want Claude to call a hosted scraping service as a tool, that is a different job, covered in our MCP server comparison and the connectors post. The script and the encoding bug below are from a real run against a sandbox site; the Claude Code behavior is from Anthropic's own documentation.
Which Claude Code mode fits the job
There are four ways Claude Code gets web data, and picking the wrong one is the usual source of the complaint:
| Mode | Good for | Poor for |
|---|---|---|
Built-in WebFetch / WebSearch | One-off questions about a page or a topic | Bulk extraction, exact field values, JavaScript-heavy pages |
| Claude writes a script, you run it | Repeatable extraction from a known site, with tests | Sites that need a logged-in or anti-bot-defended session |
| MCP server or skill from a scraping vendor | Platform data (marketplaces, social, maps) without maintaining selectors | Sites the vendor doesn't cover |
| A browser tool (Playwright, a headless engine) | Pages that only render with JavaScript | Anything where plain HTTP already returns the data |
This post covers the second row. The reason to prefer it for anything you will run more than once is that a script is a file you can read, test and re-run, while a WebFetch answer is a one-time paraphrase.
Why WebFetch can't be your scraper
The Claude Code tools reference describes WebFetch plainly: Claude asks a question about the page, and a separate model call reads the page and returns an answer. Some practical consequences from the same docs:
- WebFetch reads the first 100,000 characters of a page, and the `web-fetch` subagent reads pages of up to about 48,000 characters in full. A long listing page is truncated.
- Results are cached for 15 minutes (`CLAUDE_CODE_WEBFETCH_CACHE_TTL_MS` changes that), so a re-check can describe the page as it was before your change.
- If a fetch redirects to a different host, WebFetch returns the new URL and no content.
- It refuses `localhost` and hostnames without a dot; the docs suggest asking Claude to use `curl` through Bash for local servers.
- Claude's reply can leave out anything it didn't ask about. Press `Ctrl+O` in the terminal to see the question it asked and the answer it got back.
The docs' own advice when WebFetch misses something is to ask Claude to run curl on the URL through the Bash tool to get the raw page. That sentence is the whole workflow below: get the raw page, then write code against it.
The fetch-first loop
The sandbox target is books.toscrape.com, a site built for scraping practice. Step one is yours, not Claude's: save the real HTML so Claude is looking at the markup and not guessing at it.
curl -s https://books.toscrape.com/catalogue/category/books/mystery_3/index.html -o mystery.html
grep -c 'class="product_pod"' mystery.html # 20
Then give Claude a narrow, specific task. Something like:
mystery.html is a saved category page from books.toscrape.com. Write
books_scraper.py that fetches the live page with requests and parses
title, price in GBP as a float, star rating as an int, in-stock as a bool,
and the absolute product URL for each book. Use BeautifulSoup selectors that
exist in mystery.html. Print CSV to stdout. Fail with a clear error if zero
rows are parsed or a price is outside 0-1000. Don't add retries or proxies.
The constraints matter. "Selectors that exist in mystery.html" stops invented class names, and "fail with a clear error" gets you the assertions. We ran a script of that shape; this is the version that works:
import csv
import re
import sys
import requests
from bs4 import BeautifulSoup
URL = "https://books.toscrape.com/catalogue/category/books/mystery_3/index.html"
RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
def parse(html, base: str) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
rows = []
for pod in soup.select("article.product_pod"):
link = pod.select_one("h3 a")
rating_word = pod.select_one("p.star-rating")["class"][1]
rows.append(
{
"title": link["title"],
"price_gbp": float(re.sub(r"[^0-9.]", "", pod.select_one("p.price_color").text)),
"rating": RATINGS[rating_word],
"in_stock": "In stock" in pod.select_one("p.instock").text,
"url": requests.compat.urljoin(base, link["href"]),
}
)
return rows
if __name__ == "__main__":
resp = requests.get(URL, headers={"User-Agent": "demo-scraper/1.0"}, timeout=20)
resp.raise_for_status()
rows = parse(resp.content, URL) # bytes: let BeautifulSoup detect the charset
assert rows, "selector drift: zero products parsed"
assert all(0 < r["price_gbp"] < 1000 for r in rows), "price parse looks wrong"
writer = csv.DictWriter(sys.stdout, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
print(f"# {len(rows)} rows", file=sys.stderr)
Run with requests and beautifulsoup4 installed, it printed 20 rows, starting with Sharp Objects,47.82,4,True,.... Two things in it are deliberate.
First, the assertions. A scraper that quietly returns zero rows after a redesign is worse than one that crashes, because nobody notices until the downstream report is empty. Second, resp.content and the regex on the price. Both come from a bug that is a good illustration of why you read the output.
The £ bug
Our first version used resp.text and stripped the price with .lstrip("££"). It produced correct numbers, so it passed. But why would a pound sign need two characters of stripping? The cause turned out to be the response: the server sends content-type: text/html with no charset, and requests falls back to ISO-8859-1, which turns the UTF-8 £ into £. requests itself reported encoding: ISO-8859-1 while apparent_encoding was utf-8.
Stripping the junk characters hides the problem: the same mis-decoding silently corrupts every other non-ASCII character on the page, including titles with accents. Passing raw bytes to BeautifulSoup, which reads the page's own charset declaration, fixes the cause. When Claude hands you code with a workaround for something that "just appears" in the data, ask what the cause is.
Make it repeatable
Once the script works, put the rules in CLAUDE.md so every later session follows them. This is our suggestion, not something we benchmarked:
## Scraping rules
- Save a real HTML sample before writing selectors; never invent class names.
- Every scraper asserts rows > 0 and sanity-checks numeric fields.
- Pass `response.content` (bytes) to the parser, not `response.text`.
- Set a descriptive User-Agent, a timeout, and `raise_for_status()`.
- Check robots.txt and the site's terms before the first request.
For recurring runs, the usual tools apply: cron, a CI job, and a saved fixture file so the parser has a test that doesn't hit the network. Our BeautifulSoup tutorial and Scrapy tutorial cover the next steps when one page becomes thousands.
When Claude declines
Reports of Claude Code declining scraper requests are easy to find. Thread titles from r/webscraping, r/ClaudeCode and r/claude over the past year include "Claude Code refusing to build scraper. Any way around this?", "Why is it so fussed over web scraping now?" and "Claude flat out refusing to crawl/scrape websites". We read those threads, and the suggested fixes fall into two groups.
The first group is a better description of the task. One commenter reports never having an issue and says to ask it to use a specific tool such as Playwright to accomplish a particular task instead of asking it to "build a scraper". That fits what we'd expect: a request with a named target, a named data field and a stated purpose is easier to judge than a generic one.
The second group is claiming authorization you don't have: replies joke about telling Claude "we got permission from the website", or having it draft a permission email and then answering it yourself. We'd skip that. Whether you may scrape a site is a question about the site's terms, the data and your jurisdiction (see is web scraping legal in 2026), and a sentence typed into a chat doesn't change the answer.
What to do instead:
- State what you're collecting and why, name the specific pages or fields, and note that they're public.
- Check robots.txt and the terms first; if the site prohibits automated access, ask for permission for real, or use its official API.
- If an official API or a licensed dataset covers the data, use that. A structured API returns the fields without anyone writing selectors.
- If the request is declined for a reason that doesn't apply to your case, rephrase the actual facts. Don't invent facts.
Where the script approach stops
A script Claude writes is still plain HTTP plus a parser. It won't help when:
- The page builds its data with JavaScript. Fetch the page and the rows aren't there; use a browser engine such as [Playwright](/blog/web-scraping-with-playwright), or [a lightweight JS-executing browser](/blog/web-scraping-with-lightpanda), or find the JSON endpoint the page calls.
- The site fingerprints TLS or blocks datacenter IPs. A scraper that works on a practice site often returns 403 on a real storefront; see [why a scraper gets 403 on the server but works locally](/blog/scraper-403-on-server-works-locally).
- You need many platforms. Maintaining selectors for each one is the work, not the writing of the first script.
For platforms where you want the data and not the maintenance, give Claude Code a tool instead of a script. Adding a hosted MCP server is one command; the docs' syntax takes the endpoint and a header:
claude mcp add --transport http crawlora https://mcp.crawlora.net/mcp \
--header "Authorization: Bearer $CRAWLORA_API_KEY"
Or call the REST API from the script Claude writes:
import requests
r = requests.get(
"https://api.crawlora.net/api/v1/amazon/search",
params={"k": "mechanical keyboard"},
headers={"x-api-key": "YOUR_API_KEY"},
)
for item in r.json()["data"]:
print(item["asin"], item["list_price"], item["link"])
The response is normalized JSON, with proxies, rendering and bot handling done behind the endpoint. There is an official Python SDK if you'd rather not build the request yourself.
Wrap-up
Use WebFetch to ask a page a question and a script to collect data. Give Claude the real HTML before it writes selectors, make the script assert on its own output, and treat any "this just works" cleanup as a bug to explain. If it declines, describe the task honestly and check that you're allowed to do it, because the answer to that question is yours, not the model's.
Give Claude Code structured web data instead of selectors
Hosted MCP server and REST API, managed proxies and rendering, pay-on-success billing. 2,000 free credits/month, no card.
Related reading
- Web scraping with AI: the wider picture of how agents and LLMs get web data
- Best web scraping MCP servers and skills for Claude Code: when to hand Claude a tool instead of a script
- Best web data connectors for Claude: the Claude.ai connector side of the same question
- Web scraping with Python: the requests and parser basics the script above uses
- BeautifulSoup tutorial: selectors in depth
- Is web scraping legal in 2026: the question the model can't answer for you
- Scraping sites that block bots: what changes when a plain request stops working
Frequently asked questions
Can Claude Code scrape websites?
Yes, in two different ways. Its built-in WebFetch tool answers questions about a page, and it can write and run a scraper script with Bash. For bulk or repeatable extraction the script is the right choice, because WebFetch usually returns an answer drawn from the page rather than the page itself.
Why does Claude Code miss data when it fetches a page?
According to the Claude Code docs, for most pages Claude does not see the full text: it asks a question about the page and a separate model call reads the page and returns an answer. WebFetch reads at most the first 100,000 characters, caches pages for 15 minutes, and returns no content when a redirect changes the host. Press Ctrl+O to see what Claude asked, or ask it to run curl through the Bash tool for the raw page.
Why does Claude Code sometimes refuse to build a scraper?
Reddit threads in r/webscraping, r/ClaudeCode and r/claude report refusals, and commenters say a request with a specific tool, target and task works better than a generic request to build a scraper. We could not verify the model's reasoning from outside. Describe the real task accurately, check the site's robots.txt and terms, and use an official API where one covers the data.
Should I tell Claude I have permission to scrape a site?
Only if it is true. Some Reddit replies joke about claiming permission or drafting a permission email and answering it yourself. Whether you may scrape a site depends on its terms, the data and your jurisdiction, and a sentence in a chat does not change that.
How do I give Claude Code a scraping tool instead of a script?
Add an MCP server. Per the Claude Code docs the syntax is claude mcp add --transport http <name> <url>, with a --header flag for an API key or bearer token, for example claude mcp add --transport http crawlora https://mcp.crawlora.net/mcp --header "Authorization: Bearer $CRAWLORA_API_KEY".
