Playground Sign in Start free

Build a Python Web Crawler (and When to Use a Crawl API)

Download runnable code Sign in to prefill your key
Python web crawler (requests and a queue) Download Python
The same crawl with the Crawl API Download Python
1

How a web crawler works

A web crawler starts from one URL, downloads the page, extracts its links, and adds the links it has not seen yet to a queue; it repeats until the queue is empty or a page limit is reached. In Python that takes requests, a deque and the standard library's HTML parser. Our crawler below read 50 pages of books.toscrape.com in 37 seconds, with robots.txt honoured and half a second between requests.

  1. Put the start URL in a queue and in a set of seen URLs.
  2. Take the next URL from the queue and download it.
  3. Parse the page: keep its title, collect its <a href> links.
  4. Make each link absolute, drop the #fragment, keep it if it is on the same host and not seen yet.
  5. Stop at the page limit, and write what you found.

That is the whole algorithm (breadth first). The hard parts are everything around it, covered in section 4, and that is where a crawl API job helps.

2

The Python crawler

About 55 lines of code, no framework. It stays on the start URL's host, reads each URL once, honours robots.txt with urllib.robotparser, waits DELAY seconds between requests, and writes every URL with its status code and title to pages.csv.

Python
#!/usr/bin/env python3
"""A small Python web crawler: requests, a queue (breadth first) and the standard library's HTML parser.

Starts from one URL, stays on its host, reads each URL once, follows links until MAX_PAGES,
honours robots.txt and waits between requests. Writes every URL with its status and title to pages.csv.

    pip install requests
    python3 crawler.py
"""
import csv
import time
from collections import deque
from html.parser import HTMLParser
from urllib import robotparser
from urllib.parse import urldefrag, urljoin, urlparse

import requests

START = "https://books.toscrape.com/"
MAX_PAGES = 50
DELAY = 0.5          # seconds between two requests: be polite
AGENT = "my-crawler/1.0"


class PageParser(HTMLParser):
    """Collects the <a href> links and the <title> of one HTML page."""

    def __init__(self):
        super().__init__()
        self.links, self.title, self._in_title = [], "", False

    def handle_starttag(self, tag, attrs):
        if tag == "a" and dict(attrs).get("href"):
            self.links.append(dict(attrs)["href"])
        elif tag == "title":
            self._in_title = True

    def handle_endtag(self, tag):
        if tag == "title":
            self._in_title = False

    def handle_data(self, data):
        if self._in_title:
            self.title += data


host = urlparse(START).netloc
robots = robotparser.RobotFileParser(urljoin(START, "/robots.txt"))
robots.read()
http = requests.Session()
http.headers["User-Agent"] = AGENT

queue, seen, rows = deque([START]), {START}, []
started = time.time()
while queue and len(rows) < MAX_PAGES:
    url = queue.popleft()
    if not robots.can_fetch(AGENT, url):
        rows.append([url, "robots.txt", ""])
        continue
    try:
        response = http.get(url, timeout=30)
    except requests.RequestException as err:
        rows.append([url, type(err).__name__, ""])
        continue
    page = PageParser()
    if "html" in response.headers.get("Content-Type", ""):
        page.feed(response.text)
    rows.append([url, response.status_code, " ".join(page.title.split())])
    for href in page.links:
        link = urldefrag(urljoin(url, href)).url        # absolute, without #fragment
        if urlparse(link).netloc == host and link not in seen:
            seen.add(link)
            queue.append(link)
    time.sleep(DELAY)

with open("pages.csv", "w", newline="") as f:
    csv.writer(f).writerows([["url", "status", "title"], *rows])
print(f"{len(rows)} pages in {time.time() - started:.0f} s; {len(queue)} URLs still in the queue")
3

Run it

Run it
pip install requests
python3 crawler.py
Output
50 pages in 37 s; 531 URLs still in the queue
pages.csv (first rows)
url,status,title
https://books.toscrape.com/,200,All products | Books to Scrape - Sandbox
https://books.toscrape.com/index.html,200,All products | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/category/books_1/index.html,200,Books | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/category/books/travel_2/index.html,200,Travel | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/category/books/mystery_3/index.html,200,Mystery | Books to Scrape - Sandbox
...

It works on a sandbox built for scraping. Note the first two rows: / and /index.html are the same page, read twice. With 531 URLs still queued after 50 pages, the queue also shows how fast a crawl grows.

4

What the do-it-yourself crawler does not handle

Point the same script at a real site and the gaps show up quickly:

ProblemYour own crawlerOne Crawl API job
Pages built with JavaScriptGets an empty shell; needs a headless browser to run and scale."page": {"js": true} renders each page (5 credits a page).
Sites that block plain requestsSaves the block page as if it were content, or stops.Each page goes through the Ujeebu API's proxies and block handling; a refused page reads blocked, never as content.
robots.txt and Crawl-delayUp to you (the script above checks robots.txt).Honoured for UjeebuBot, then *; a Crawl-delay is respected up to 30 seconds.
DuplicatesThe same page under two URLs is read twice.A page whose canonical link points to another page of the job is recorded as duplicate.
Cost and sizeRuns until the queue is empty or you stop it.A free quote gives the most it can cost; max_credits is a hard cap.
Failures and resumingOne exception can lose the run.Every page has a state and an error class; a resumable cursor and a checksummed archive kept 72 hours.
InfrastructureYour servers, queue, retries and monitoring.None: start a job, read the results.
Build or call?

Write your own crawler when the site is small, plain HTML and friendly, or when you need full control. Use a crawl job when the site needs JavaScript, blocks plain requests, or is big enough that retries, duplicates and cost control would take longer than the crawl.

5

The same crawl with the Crawl API

The same 50 pages as one job: get the free quote, start the job with max_credits set to the quote's ceiling, wait for finished, then read the page records and write the same pages.csv. Plain HTML without JavaScript costs 1 credit a page.

cURL
# 1. The quote: the most this crawl can cost (nothing is started)
curl -s -X POST https://api.ujeebu.com/crawl/quote \
  -H "ApiKey: YOUR_API_KEY" -H "Content-Type: application/json" \
  -d '{"urls": ["https://books.toscrape.com/"], "scope": {"max_pages": 50},
       "format": "html", "page": {"js": false}}'

# 2. The job, capped at the quote's credits_ceiling
curl -s -X POST https://api.ujeebu.com/crawl \
  -H "ApiKey: YOUR_API_KEY" -H "Content-Type: application/json" \
  -d '{"urls": ["https://books.toscrape.com/"], "scope": {"max_pages": 50},
       "format": "html", "page": {"js": false}, "max_credits": 50}'

# 3. Status, then the page records, 50 at a time
curl -s https://api.ujeebu.com/crawl/JOB_ID -H "ApiKey: YOUR_API_KEY"
curl -s "https://api.ujeebu.com/crawl/JOB_ID/pages?after=0&limit=50" -H "ApiKey: YOUR_API_KEY"
Python
#!/usr/bin/env python3
"""The same crawl as one Ujeebu Crawl API job: get the quote, cap the job at it, read the page records.

The API reads every page through the Ujeebu API (proxies, block handling, JavaScript when you ask for
it), honours robots.txt, spots duplicates by their canonical URL and stops at max_credits.
Writes pages.csv like the do-it-yourself crawler.

    pip install requests
    UJEEBU_API_KEY=your-key python3 crawl_with_api.py
"""
import csv
import os
import time

import requests

API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
API = "https://api.ujeebu.com"

CRAWL = {
    "urls": ["https://books.toscrape.com/"],
    "scope": {"max_pages": 50},
    "format": "html",
    "page": {"js": False},     # set True for sites that render with JavaScript
}

http = requests.Session()
http.headers["ApiKey"] = API_KEY


def api(method, path, **kwargs):
    response = http.request(method, API + path, timeout=60, **kwargs)
    if response.status_code >= 400:
        raise SystemExit(f"{method} {path}: {response.status_code} {response.text}")
    return response.json()


started = time.time()
quote = api("POST", "/crawl/quote", json=CRAWL)
print(f"Quote: {quote['credits_per_page']} credit a page, at most {quote['credits_ceiling']} credits")
job = api("POST", "/crawl", json={**CRAWL, "max_credits": quote["credits_ceiling"]})
while not job.get("finished"):
    time.sleep(5)
    job = api("GET", f"/crawl/{job['job_id']}")

rows, after = [], 0
while True:
    batch = api("GET", f"/crawl/{job['job_id']}/pages", params={"after": after, "limit": 50})
    rows += [[p["url"], p.get("http_status") or p.get("error_class"), p.get("title", "")] for p in batch["pages"]]
    if not batch["has_more"]:
        break
    after = batch["next_after"]

with open("pages.csv", "w", newline="") as f:
    csv.writer(f).writerows([["url", "status", "title"], *rows])
print(f"{len(rows)} pages in {time.time() - started:.0f} s: {dict(job['counts'])}")
print(f"stop_reason={job['stop_reason']}, {job['credits_used']} credits, robots.txt: {job['robots'][0]['status']}")
Output
Quote: 1 credit a page, at most 50 credits
GET /crawl/JOB_ID (trimmed)
{
  "job_id": "c_a0d0dcea-fa64-49bd-b975-4c41171a6e87",
  "counts": {"discovered": 50, "done": 50, "failed": 0, "in_progress": 0, "pending": 0, "skipped": 0},
  "credits_used": 50,
  "max_credits": 50,
  "errors": {},
  "robots": [{"host": "books.toscrape.com", "http_status": 404, "status": "missing"}]
}
pages.csv (first rows)
url,status,title
https://books.toscrape.com/,200,All products | Books to Scrape - Sandbox
https://books.toscrape.com/index.html,200,All products | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/category/books_1/index.html,200,Books | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/category/books/travel_2/index.html,200,Travel | Books to Scrape - Sandbox
...

The same 50 pages as the Python crawler, for 50 credits, exactly the quote. The crawl ran on our side: your script only waits and reads the results. "status": "missing" is the honest state of that site's robots.txt (it answers 404), so every page was allowed. This site declares no canonical links, so / and /index.html are two pages here too; on a site that declares them, the second would be recorded as duplicate.

6

Side by side

Python crawlerCrawl API job
Pages read5050
Code you maintainThe crawler, the parser, the queueAbout 40 lines that call the API
JavaScript, blocks, duplicatesNot handledHandled per page, with an honest state
Cost known before the startYour own servers and timeFree quote: at most 50 credits here

Next steps with the same job: find all pages on a website (sitemap list plus link crawl), or convert a website to Markdown for LLMs.

Skip the crawler, keep the control

The free sizer lists a site's sitemap URLs and quotes the crawl before you spend a credit.

?

Frequently Asked Questions

How do I build a web crawler in Python?

Keep a queue of URLs to visit and a set of URLs already seen. Take a URL from the queue, download it with requests, parse its links, and add the new ones on the same host to the queue, until you reach a page limit. The crawler on this page does that, and also honours robots.txt and waits between requests.

How do I crawl an entire website with Python?

Start from the home page and follow links breadth first, staying on the site's host and reading each URL once. For a real site, also handle retries, blocked requests, pages that need JavaScript, duplicates and a stop condition. A crawl API job does those for you and returns every page with its status.

When should I use a crawl API instead of my own crawler?

When the site renders with JavaScript, blocks plain requests, or is large enough that retries, duplicates and cost control take more time than the crawl itself. A free quote gives the most a crawl can cost before it starts, and max_credits is a hard cap: the job stops before a page that would pass it.

How much does the API version of this crawl cost?

Plain HTML costs 1 credit a page, so the 50 pages of this example cost 50 credits. With JavaScript rendering a page costs 5 credits. Failed and blocked pages are not billed.

Does the Crawl API respect robots.txt?

Yes, for the UjeebuBot token, then *. A disallowed page is recorded with error_class "robots", never fetched, and costs nothing, and a Crawl-delay is respected up to 30 seconds.