---
title: "How to Build a Web Crawler in Python"
description: "Crawl a whole e-commerce site with Requests and Beautiful Soup, export its products to CSV, then run the same crawl as one API call with Zenrows Crawl."
---
# How to Build a Web Crawler in Python

> Crawl a whole e-commerce site with Requests and Beautiful Soup, export its products to CSV, then run the same crawl as one API call with Zenrows Crawl.

Source: https://www.zenrows.com/blog/web-crawler-python

A Python web crawler starts from one URL, follows the links it finds, skips the pages it has already seen, and keeps going until it has covered the site. Building a production-grade web crawler requires balancing performance, memory management, and stealth. At scale, simple scripts quickly crash due to a bloated crawl queue, infinite loops caused by [spider traps](https://www.zenrows.com/glossary/web-crawling/what-is-a-spider-trap), and aggressive IP rate-limiting.

We've designed this guide to take you from a basic script to a robust, production-ready crawler. You'll build a web crawler in Python with Requests and Beautiful Soup that discovers every product on a demo store and saves their names, prices, and images to CSV. Then you'll run the same discover, follow, and dedupe loop as one API call with [Zenrows Crawl](https://www.zenrows.com/products/crawl).

* [Building your first Python web crawler](#build-your-first-python-web-crawler).  
* [Making your Python web crawler production-ready](#make-your-python-web-crawler-production-ready).  
* [Crawling a site in one API call with Zenrows Crawl](#crawl-a-site-in-one-api-call-with-zenrows-crawl).  
* [Web crawling tools for Python](#web-crawling-tools-for-python).  
* [Web crawling best practices for Python](#web-crawling-best-practices-in-python).

## Key Takeaways
- At its core, a web crawler follows a continuous cycle: fetching a page, parsing HTML for links, filtering out seen URLs, and adding new ones back into a crawl queue.
- A Python set tracks visited URLs with fast lookups. For long or distributed crawls, move it to a shared store such as Redis so every worker sees it and a restarted crawl can resume.
- With the same 20-page limit, a priority queue that visits product listing pages first collected all 188 products on the demo store, against 92 for the first-in, first-out crawler.
- Threads speed up a crawler because most of its time is spent waiting on the network. Tune the worker count to the site and your bandwidth rather than maximizing it.
- Production-grade crawlers must implement exponential backoff retries and persistent Sessions to handle network flakiness and reduce overhead.
- Web crawling is often stalled due to IP bans, rate limiting, and outright anti-bot blocks.
- Zenrows Crawl runs the whole discover, follow, and dedupe loop as one API call and fetches each page through Fetch with Adaptive Stealth Mode to get past anti-bot protection.

## What Is a Web Crawler in Python?
Web pages usually contain many internal links to resources and other pages, such as navigation menus, pagination, related posts, and sometimes hidden or dynamically loaded links. [Web crawlers](https://www.zenrows.com/glossary/web-crawling/what-is-a-web-crawler), often starting from the main page (home page), navigate the site by discovering and following links.

Their purpose is to gather information from the website, whether for indexing, data analysis, or building a map of its structure. Search engines like Google use this process on a massive scale to index content across the internet, but web crawling techniques can also be applied to individual sites or domains.

[Web crawling and scraping](https://www.zenrows.com/blog/web-crawling-vs-web-scraping) share some similarities, though. However, their operations differ slightly. While a web crawler discovers and indexes web pages, a web scraper extracts and stores specific data from those pages.

If you want to create a production-ready web crawler, you'll follow a few steps that let you add new URLs to your crawl queue continuously. That said, you also want your web crawler to avoid common problems like link duplication, endless crawling, latency, IP bans, etc.

Let's visualize the crawling process to better understand how it works.

### The Crawler Life Cycle
A web crawler is recursive, starting with the initial page fetch. It then extracts new links, filters out URLs it has already seen, and adds the new ones back to the queue to restart the process.

Here's a visual representation of the crawling life cycle.

![The crawler life cycle: from a start URL, fetch a page, find its links, skip the URLs already seen, queue the new ones, and fetch the next page](https://www.zenrows.com/blog/_img/web-crawler-python-life-cycle.png)

Now that you know what a web crawler is and how it works, it's time to build one.

## Build Your First Python Web Crawler
We'll now crawl this [E-commerce Challenge website](https://www.scrapingcourse.com/ecommerce/). The site has many pages. And these include links to paginated products, shopping carts, category pages, and more. Your web crawler will follow some of these links and extract specific product details, including product names, prices, URLs, and image links.

See what the page looks like below:

![The ScrapingCourse.com demo store's Shop page, showing 188 products across 12 paginated listing pages](https://www.zenrows.com/blog/_img/web-crawler-python-scrapingcourse-store.png)

Before jumping into the tutorial, let's start with the requirements.

### Prerequisites for Python Web Crawling
You'll need the following tools to get started:

* **Python 3+**: [Download the latest version](https://www.python.org/downloads/), install it, and add it to your system's path.  
* **A Python IDE**: Visual Studio Code with the [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) extension or [PyCharm Community Edition](https://www.jetbrains.com/pycharm/download/) will do.

You'll also need an HTTP client and an HTML parser for web crawling. The two most popular Python packages for that are:

* [**Requests**](https://requests.readthedocs.io/en/latest/): A powerful HTTP client library that facilitates the execution of HTTP requests and handles their responses.  
* [**Beautiful Soup**](https://www.crummy.com/software/BeautifulSoup/bs4/doc/): A full-featured HTML and XML parser that exposes a complete API to explore the DOM, select HTML elements, and retrieve data from them.

Install them both using the following command:

```bash
pip3 install beautifulsoup4 requests
```

Great\! You're ready to begin. 

The following sections provide a step-by-step guide to building your first web crawler in Python.

### Step 1: Follow All the Links on a Website
In this step, you'll design your crawling logic to discover and follow all the links on the target website. Before that, you'll make a simple request to the target website. 

Create a `crawler` function with a request to the target page. Behind the scenes, the `get` method performs an HTTP GET request to the specified URL and returns its full-page HTML:

<!-- crawler.py -->
```python
# pip3 install requests
import requests

# request the target URL
def crawler():
    response = requests.get("https://www.scrapingcourse.com/ecommerce/")
    response.raise_for_status()
    print(response.text)

# execute the crawler
crawler()
```

The above is a simple GET request to the target website that only returns its HTML as a response:

```html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <!--- ... --->
  
    <title>Ecommerce Test Site to Learn Web Scraping - ScrapingCourse.com</title>
    
  <!--- ... --->
</head>
<body class="home archive ...">
    <p class="woocommerce-result-count">Showing 1-16 of 188 results</p>
    <ul class="products columns-4">

        <!--- ... --->

    </ul>
</body>
</html>
```

> **Skip the blocks.** [Try Zenrows free](https://app.zenrows.com/register?primitive=crawl) and get clean web data without the anti-bot fight.

Let's modify the current code to a full-blown web crawler.  

Add Beautiful Soup to your imports and set the target URL as the initial link in the `urls_to_visit` list.

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4

# ...
from bs4 import BeautifulSoup

target_url = "https://www.scrapingcourse.com/ecommerce/"

# initialize the list of discovered URLs
urls_to_visit = [target_url]
```

Modify the `crawler` function to run continuously using a `while` loop as long as the `urls_to_visit` isn't empty. Get the next link from the front of the URL list and parse the website's HTML with Beautiful Soup. Extract all `href` attributes from `a` tags and convert them to absolute URLs against the page they were found on. Then, update the `urls_to_visit` list with newly discovered links.

Here's the modified code:

<!-- crawler.py -->
```python
# ...

def crawler():

    while urls_to_visit:

        # get the page to visit from the list
        current_url = urls_to_visit.pop(0)

        # ...

        # parse the HTML
        soup = BeautifulSoup(response.text, "html.parser")

        # collect all the links
        link_elements = soup.select("a[href]")
        for link_element in link_elements:
            url = link_element["href"]

            # convert links to absolute URLs
            absolute_url = requests.compat.urljoin(current_url, url)

            # ensure the crawled link belongs to the target domain and isn't queued yet
            if (
                absolute_url.startswith(target_url)
                and absolute_url not in urls_to_visit
            ):
                urls_to_visit.append(absolute_url)
```

The code might run an endless crawl at this point because nothing tells it when to stop. Setting **a crawl limit ensures the crawler stops after visiting a set number of pages, preventing excessive or infinite crawling**. Large crawlers often pair it with a [crawl depth](https://www.zenrows.com/glossary/web-crawling/what-is-crawl-depth) limit, which caps how many link hops the crawler follows from the start page.

To apply a crawl limit, set the maximum number of pages to 20. Then, use a crawl counter to track how many pages the crawler has visited. Update the `while` loop logic with the following changes:

<!-- crawler.py -->
```python
# set a maximum crawl limit
max_crawl = 20


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    while urls_to_visit and crawl_count < max_crawl:

        # ...

        # ... crawling logic

        # update the crawl counter
        crawl_count += 1
```

Finally, print the `urls_to_visit` list and execute the `crawler` function:

<!-- crawler.py -->
```python
# ...
def crawler():
    # ...

    # print the discovered URLs
    print(urls_to_visit)

# execute the crawl
crawler()
```

Combine the snippets at this point, and you'll get the following complete and updated code:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup

target_url = "https://www.scrapingcourse.com/ecommerce/"

# initialize the list of discovered URLs
urls_to_visit = [target_url]

# set a maximum crawl limit
max_crawl = 20


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    while urls_to_visit and crawl_count < max_crawl:

        # get the page to visit from the list
        current_url = urls_to_visit.pop(0)

        # request the target URL
        response = requests.get(current_url)
        response.raise_for_status()

        # parse the HTML
        soup = BeautifulSoup(response.text, "html.parser")

        # collect all the links
        link_elements = soup.select("a[href]")
        for link_element in link_elements:
            url = link_element["href"]

            # convert links to absolute URLs
            absolute_url = requests.compat.urljoin(current_url, url)

            # ensure the crawled link belongs to the target domain and isn't queued yet
            if (
                absolute_url.startswith(target_url)
                and absolute_url not in urls_to_visit
            ):
                urls_to_visit.append(absolute_url)

        # update the crawl count
        crawl_count += 1

    # print the discovered URLs
    print(urls_to_visit)


# execute the crawl
crawler()
```

The above code outputs the URLs the crawler discovered during its first 20 page visits:

```json
[
    'https://www.scrapingcourse.com/ecommerce/product/aim-analog-watch/',
    'https://www.scrapingcourse.com/ecommerce/?add-to-cart=2740',
    'https://www.scrapingcourse.com/ecommerce/product/ajax-full-zip-sweatshirt/',

    // ... omitted for brevity,

    'https://www.scrapingcourse.com/ecommerce/page/2/',
    'https://www.scrapingcourse.com/ecommerce/page/1/',

    // ... omitted for brevity,
]
```

Great! It's time to filter the above links and extract data from specific product pages. If you only need the links, our guide on how to [find all URLs on a domain](https://www.zenrows.com/blog/find-all-urls-on-a-domain) covers more ways to collect them.

### Step 2: Extract Data From the Crawler
Once you have the links, the next step is to extract data from selected pages (specifically the product listing pages). To achieve this, you'll modify your web spider to scrape product data only when the currently crawled URL points to a product listing page. Reading the same repeated records from a set of paginated listings is known as [list crawling](https://www.zenrows.com/blog/guide-to-list-crawling).

First, you need to understand the format of the product listing page URL. This will help you create a solid URL regex to distinguish listing links from other links.

Open the target site via a browser and navigate to the second product page (page 2). You'll see it has the following URL, with the path parameter `/page/2/`:

```bash
https://www.scrapingcourse.com/ecommerce/page/2/
```

The page number in the path parameter changes dynamically as you navigate the paginated product pages.

Use Python's regex to match this path parameter at the end of the URL, so variants such as add-to-cart links with a query string don't match. Then, create an empty list (`product_data`) to collect scraped data:

<!-- crawler.py -->
```python
# ...

import re

# ...

# create a regex pattern for product listing page URLs
url_pattern = re.compile(r"/page/\d+/$")

# define a list to collect scraped data
product_data = []

# ... crawler function
```

Implement the scraping logic only if a URL's path matches the defined regex. Finally, append the extracted data to the `product_data` list and print it after executing the crawler:

<!-- crawler.py -->
```python
# ...

def crawler():
    # ...

    while urls_to_visit and crawl_count < max_crawl:

        # ...

        # extract content only if the current URL matches the regex pattern
        if url_pattern.search(current_url):
            # get the parent element
            product_containers = soup.find_all("li", class_="product")

            # scrape product data
            for product in product_containers:
                data = {
                    "Url": product.find("a", class_="woocommerce-LoopProduct-link")[
                        "href"
                    ],
                    "Image": product.find("img", class_="product-image")["src"],
                    "Name": product.find("h2", class_="product-name").text,
                    "Price": product.find("span", class_="price").text,
                }

                # append extracted data
                product_data.append(data)

            # ...
# ...

# print the extracted data
print(product_data)
```

Here's what the full code looks like at this point:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
import re
import csv

target_url = "https://www.scrapingcourse.com/ecommerce/"

# initialize the list of discovered URLs
urls_to_visit = [target_url]

# set a maximum crawl limit
max_crawl = 20

# create a regex pattern for product listing page URLs
url_pattern = re.compile(r"/page/\d+/$")

# define a list to collect scraped data
product_data = []


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    while urls_to_visit and crawl_count < max_crawl:

        # get the page to visit from the list
        current_url = urls_to_visit.pop(0)

        # request the target URL
        response = requests.get(current_url)
        response.raise_for_status()

        # parse the HTML
        soup = BeautifulSoup(response.content, "html.parser")

        # collect all the links
        for link_element in soup.find_all("a", href=True):
            url = link_element["href"]

            # convert links to absolute URLs
            absolute_url = requests.compat.urljoin(current_url, url)

            # ensure the crawled link belongs to the target domain and isn't queued yet
            if (
                absolute_url.startswith(target_url)
                and absolute_url not in urls_to_visit
            ):
                urls_to_visit.append(absolute_url)

        # extract content only if the current URL matches the regex page pattern
        if url_pattern.search(current_url):
            # get the parent element
            product_containers = soup.find_all("li", class_="product")

            # scrape product data
            for product in product_containers:
                data = {
                    "Url": product.find("a", class_="woocommerce-LoopProduct-link")[
                        "href"
                    ],
                    "Image": product.find("img", class_="product-image")["src"],
                    "Name": product.find("h2", class_="product-name").get_text(),
                    "Price": product.find("span", class_="price").get_text(),
                }

                # append extracted data
                product_data.append(data)

        # update the crawl count
        crawl_count += 1


# execute the crawl
crawler()

# print the extracted data
print(product_data)
```

The code filters the URLs to only product listing pages and outputs the scraped data as shown:

```json
[
    {
        "Url": "https://www.scrapingcourse.com/ecommerce/product/atlas-fitness-tank/",
        "Image": "https://www.scrapingcourse.com/ecommerce/wp-content/uploads/2024/03/mt11-blue_main.jpg",
        "Name": "Atlas Fitness Tank",
        "Price": "$18.00"
    },
    // ...omitted for brevity
    {
        "Url": "https://www.scrapingcourse.com/ecommerce/product/zoltan-gym-tee/",
        "Image": "https://www.scrapingcourse.com/ecommerce/wp-content/uploads/2024/03/ms06-blue_main.jpg",
        "Name": "Zoltan Gym Tee",
        "Price": "$29.00"
    }
]
```

Your Python web crawler now scrapes data specifically from product URLs. Let's export the extracted data to a CSV in the next section.

### Step 3: Extract Data Into CSV
Data storage allows you to persist and share the scraped information for further analysis, referencing, and more. You can save the data in JSON, CSV, or a local or remote database. However, for simplicity, we'll use a CSV in this article.  
   
To store the scrape data, import Python's built-in `csv` package and specify the CSV file path. Then, write each entry to a new row:

<!-- crawler.py -->
```python
# ...
import csv

# ...

# save data to CSV
csv_filename = "products.csv"
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["Url", "Image", "Name", "Price"])
    writer.writeheader()
    writer.writerows(product_data)
```

Combine all the snippets from the previous sections with this one. Here's the full code:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
import re
import csv

target_url = "https://www.scrapingcourse.com/ecommerce/"

# initialize the list of discovered URLs
urls_to_visit = [target_url]

# set a maximum crawl limit
max_crawl = 20

# create a regex pattern for product listing page URLs
url_pattern = re.compile(r"/page/\d+/$")

# define a list to collect scraped data
product_data = []


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    while urls_to_visit and crawl_count < max_crawl:

        # get the page to visit from the list
        current_url = urls_to_visit.pop(0)

        # request the target URL
        response = requests.get(current_url)
        response.raise_for_status()

        # parse the HTML
        soup = BeautifulSoup(response.content, "html.parser")

        # collect all the links
        for link_element in soup.find_all("a", href=True):
            url = link_element["href"]

            # convert links to absolute URLs
            absolute_url = requests.compat.urljoin(current_url, url)

            # ensure the crawled link belongs to the target domain and isn't queued yet
            if (
                absolute_url.startswith(target_url)
                and absolute_url not in urls_to_visit
            ):
                urls_to_visit.append(absolute_url)

        # extract content only if the current URL matches the regex page pattern
        if url_pattern.search(current_url):
            # get the parent element
            product_containers = soup.find_all("li", class_="product")

            # scrape product data
            for product in product_containers:
                data = {
                    "Url": product.find("a", class_="woocommerce-LoopProduct-link")[
                        "href"
                    ],
                    "Image": product.find("img", class_="product-image")["src"],
                    "Name": product.find("h2", class_="product-name").get_text(),
                    "Price": product.find("span", class_="price").get_text(),
                }

                # append extracted data
                product_data.append(data)

        # update the crawl count
        crawl_count += 1


# execute the crawl
crawler()

# save data to CSV
csv_filename = "products.csv"
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["Url", "Image", "Name", "Price"])
    writer.writeheader()
    writer.writerows(product_data)
```

Run the script, and the `products.csv` file will appear in your project's folder with 92 products from the listing pages the crawler reached within its 20-page limit:

![Rows of products.csv from the crawler, with each product's name, price and URL](https://www.zenrows.com/blog/_img/web-crawler-python-products-csv.png)

That's it! You just built your first Python web crawler.

That said, you still need to optimize your crawler to make it production-ready. Let's see that next!

## Make Your Python Web Crawler Production-Ready
The current web crawling script follows links and extracts specific content. However, it needs to handle limitations such as duplicate crawls, priorities, and retries more efficiently. This section will explain how to optimize it.

### Avoid Duplicate Links
Although the current crawler validates the presence of new links in the URL list (`urls_to_visit`), this method alone doesn't efficiently filter duplicates. Once a URL leaves the list, the crawler forgets it and can queue it again.

One way to prevent duplicates is to track crawled links using a pre-filtered data type like a `set`. In addition to automatically filtering duplicates, Python's set uses a hash table, providing faster lookup with minimal delay. This results in significantly faster duplicate detection and improves performance.

To handle [deduplication](https://www.zenrows.com/glossary/web-crawling/what-is-deduplication) with a Python set, track every URL the crawler has already queued in a `visited_urls` set. Seed it with the start URL, and add each new link to the set as you queue it, so no page enters the queue twice:

<!-- crawler.py -->
```python
# ...

# create a set to track every URL the crawler has already queued
visited_urls = {target_url}

def crawler():
    # ...

    while urls_to_visit and crawl_count < max_crawl:

        # ...

        # collect all the links
        for link_element in soup.find_all("a", href=True):
            # ...

            # ensure the crawled link belongs to the target domain and hasn't been queued
            if absolute_url.startswith(target_url) and absolute_url not in visited_urls:
                visited_urls.add(absolute_url)
                urls_to_visit.append(absolute_url)

        # ... scraping logic

# ...
```

These improvements help your crawler efficiently avoid duplicate visits to previously discovered links.

However, keep in mind that **a set lives in your crawler's memory, so it grows with every URL you discover and disappears when the script stops**.

For long or distributed crawls, move the visited set to a shared store such as a Redis set, so several workers can check it and a restarted crawl can pick up where it left off. A Bloom filter is the other common option: a space-efficient probabilistic data structure that tells you whether a URL is possibly in the set or definitely not, at the cost of occasionally skipping a page it never visited.

### Add a Priority Queue
Priority queues let you prioritize specific URLs over others during the crawling process.

In this case, your spider will prioritize product listing page URLs. This technique can even extend the amount of data you can scrape, as your crawler now traverses product listing pages before other pages. **With the same 20-page limit, the prioritized crawler collects all 188 products on the store, against 92 for the first-in, first-out version.**

To prioritize specific pages, you can use Python's built-in [`queue`](https://docs.python.org/3/library/queue.html) module. It ships a `PriorityQueue` class, but two plain `Queue` objects, one for high-priority and one for low-priority URLs, keep the logic easy to read. Each `Queue` is first in, first out, so within a priority level the crawler moves [breadth-first](https://www.zenrows.com/glossary/web-crawling/breadth-first-vs-depth-first-crawling) through the site.

Import the Queue library. Then, create high and low-priority queues, replace the previous `urls_to_visit` list with these queues, and add the start URL to the low-priority queue. If a discovered URL matches the product listing page path, put it in the high-priority queue. Otherwise, push it to the low-priority queue:

<!-- crawler.py -->
```python
# ...
from queue import Queue

# ...

# instantiate the queues
high_priority_queue = Queue()
low_priority_queue = Queue()

# add the start URL to the queue
low_priority_queue.put(target_url)

# ...

def crawler():
    # ...

    while (
        not high_priority_queue.empty() or not low_priority_queue.empty()
    ) and crawl_count < max_crawl:

        # get the next URL, product listing pages first
        if not high_priority_queue.empty():
            current_url = high_priority_queue.get()
        else:
            current_url = low_priority_queue.get()

        # update the crawl count
        crawl_count += 1

        # ...

        # collect all the links
        for link_element in soup.find_all("a", href=True):
            # ...

            # ensure the crawled link belongs to the target domain and hasn't been queued
            if absolute_url.startswith(target_url) and absolute_url not in visited_urls:
                visited_urls.add(absolute_url)

                # prioritize product listing pages
                if url_pattern.search(absolute_url):
                    high_priority_queue.put(absolute_url)
                else:
                    low_priority_queue.put(absolute_url)

        # ... scraping logic
# ...
```

Great! Since you've prioritized product listing page URLs, your crawler will now target those pages first before other pages.

### Apply Request Retries and Delays
[Request retries](https://www.zenrows.com/blog/python-requests-retry) allow you to check and resend failed requests. While implementing retries, adding random or exponential delays is a good practice to avoid overloading the server, hitting its [rate limits](https://www.zenrows.com/blog/429-too-many-requests), or risking an IP ban. An exponential delay increases the wait time exponentially for each failed request. A fixed [crawl delay](https://www.zenrows.com/glossary/web-crawling/what-is-crawl-delay) between successful requests keeps the same pressure off the server.

The easiest way to implement a retry logic with exponential backoff is to use [Tenacity](https://tenacity.readthedocs.io/en/latest/), a Python library for handling retries. Install it using `pip`:

```bash
pip3 install tenacity
```

Next, import the library and add it as a `retry` decorator in a new `fetch_url` function. The `retry` decorator lets you specify the maximum number of attempts and the backoff parameters. Since the `fetch_url` function now handles requests, ensure you use it in place of the previous request code block. When a URL still fails after the last attempt, Tenacity raises a `RetryError`, so catch it and let the crawler move on to the next page:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4 tenacity
# ...
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError

# ...


# implement a request retry with exponential backoff
@retry(
    stop=stop_after_attempt(4),  # maximum number of attempts
    wait=wait_exponential(multiplier=2, min=2, max=30),  # wait 2s, 4s, then 8s
)
def fetch_url(url):
    response = requests.get(url)
    response.raise_for_status()
    return response


def crawler():
    # ...

    while (
        not high_priority_queue.empty() or not low_priority_queue.empty()
    ) and crawl_count < max_crawl:

        # ...

        # request the target URL and skip it if every retry fails
        try:
            response = fetch_url(current_url)
        except RetryError:
            print(f"Skipped {current_url} after 4 failed attempts")
            continue

        # ...

# ...
```

With the above modifications, your crawler will now automatically retry failed requests.

### Maintain a Single Crawl Session
Sessions let you reuse connections, reducing redundant TCP handshakes and persisting headers and cookies across pages. This can reduce network overheads and improve overall performance.

You can implement a session with the `Session` object from the Requests library. Create a new `session` instance and use it to update the `fetch_url` function like so:

<!-- crawler.py -->
```python
# ...

# initialize session
session = requests.Session()

# ...
def fetch_url(url):
    response = session.get(url)
    # ...
```

Splendid\! Your Python web crawler now manages HTTP requests with a session.

### Your Full Web Crawler Code
Combine the snippets from each section to see what the final code looks like:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4 tenacity
import requests
from bs4 import BeautifulSoup
import re
import csv
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError
from queue import Queue

target_url = "https://www.scrapingcourse.com/ecommerce/"

# instantiate the queues
high_priority_queue = Queue()
low_priority_queue = Queue()

# add the start URL to the queue
low_priority_queue.put(target_url)

# create a set to track every URL the crawler has already queued
visited_urls = {target_url}

# set a maximum crawl limit
max_crawl = 20

# create a regex pattern for product listing page URLs
url_pattern = re.compile(r"/page/\d+/$")

# define a list to collect scraped data
product_data = []

# initialize session
session = requests.Session()


# implement a request retry with exponential backoff
@retry(
    stop=stop_after_attempt(4),  # maximum number of attempts
    wait=wait_exponential(multiplier=2, min=2, max=30),  # wait 2s, 4s, then 8s
)
def fetch_url(url):
    response = session.get(url)
    response.raise_for_status()
    return response


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    while (
        not high_priority_queue.empty() or not low_priority_queue.empty()
    ) and crawl_count < max_crawl:

        # get the next URL, product listing pages first
        if not high_priority_queue.empty():
            current_url = high_priority_queue.get()
        else:
            current_url = low_priority_queue.get()

        # update the crawl count
        crawl_count += 1

        # request the target URL and skip it if every retry fails
        try:
            response = fetch_url(current_url)
        except RetryError:
            print(f"Skipped {current_url} after 4 failed attempts")
            continue

        # parse the HTML
        soup = BeautifulSoup(response.content, "html.parser")

        # collect all the links
        for link_element in soup.find_all("a", href=True):
            url = link_element["href"]

            # convert links to absolute URLs
            absolute_url = requests.compat.urljoin(current_url, url)

            # ensure the crawled link belongs to the target domain and hasn't been queued
            if absolute_url.startswith(target_url) and absolute_url not in visited_urls:
                visited_urls.add(absolute_url)

                # prioritize product listing pages
                if url_pattern.search(absolute_url):
                    high_priority_queue.put(absolute_url)
                else:
                    low_priority_queue.put(absolute_url)

        # extract content only if the current URL matches the regex page pattern
        if url_pattern.search(current_url):
            # get the parent element
            product_containers = soup.find_all("li", class_="product")

            # scrape product data
            for product in product_containers:
                data = {
                    "Url": product.find("a", class_="woocommerce-LoopProduct-link")[
                        "href"
                    ],
                    "Image": product.find("img", class_="product-image")["src"],
                    "Name": product.find("h2", class_="product-name").get_text(),
                    "Price": product.find("span", class_="price").get_text(),
                }

                # append extracted data
                product_data.append(data)


# execute the crawl
crawler()

# save data to CSV
csv_filename = "products.csv"
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["Url", "Image", "Name", "Price"])
    writer.writeheader()
    writer.writerows(product_data)
```

Run it, and `products.csv` now holds all 188 products on the store, because the priority queue sends the crawler through every listing page before it spends its 20-page limit anywhere else.

Bravo! You just built a robust web crawler in Python. It doesn't stop here. You still need to handle edge cases such as advanced anti-bot measures, parallel crawling, JavaScript rendering, and more.

We'll explore a solution that can handle all these in the next section.

## Crawl a Site in One API Call With Zenrows Crawl
The biggest challenge of web crawling in Python is getting blocked. Many sites use anti-bot measures to identify and stop automated access, preventing you from getting your desired data. 

To [avoid getting blocked](https://www.zenrows.com/blog/web-scraping-without-getting-blocked) during web crawling, you need to apply mitigation measures. Some strategies include setting up a custom User Agent, crawling during off-peak hours, or using proxies. However, these tips are generally more effective in simple scenarios and are less effective against complex anti-bot measures.

The other cost is the crawler itself. The link loop, the filters, the deduplication, the retries, and the queue you just wrote are all code you have to host and maintain.

[Zenrows Crawl](https://www.zenrows.com/products/crawl) runs that loop for you. Give it any public URL, such as a homepage or a category page. It follows the links on that site as deep as you choose, keeps only the URLs you want, drops duplicates, and fetches each page through [Fetch](https://www.zenrows.com/products/fetch) with Adaptive Stealth Mode to get past anti-bot protection. You get back every URL it found, and each page's HTML if you want it. **The crawler you built in this tutorial becomes one API call that runs on Zenrows' managed infrastructure, with nothing to provision.**

To try it, [sign up for Zenrows](https://app.zenrows.com/register?primitive=crawl) and open the [Crawl playground](https://app.zenrows.com/crawl). Paste the store's URL, preview the pages Crawl finds, and copy the generated Python code into your project:

![The Zenrows Crawl playground after a complete crawl of the ScrapingCourse store, with the include pattern /page/, the 12 listing pages it kept, and the generated Python code](https://www.zenrows.com/blog/_img/web-crawler-python-crawl-playground.png)

Here's the same ScrapingCourse store crawled with Crawl. The script starts from the homepage, keeps every product listing page with its HTML, then parses each page with the Beautiful Soup selectors you wrote in Step 2 and saves the products to CSV:

<!-- crawl.py -->
```python
# pip3 install requests beautifulsoup4
import csv
import json
import time
import requests
from bs4 import BeautifulSoup

headers = {"X-API-Key": "<YOUR_ZENROWS_API_KEY>"}

# start a crawl that keeps every product listing page with its HTML
response = requests.post(
    "https://api.zenrows.com/v1/crawls",
    headers=headers,
    json={
        "url": "https://www.scrapingcourse.com/ecommerce/",
        "include_patterns": ["/page/"],
        "output_format": "html",
    },
)
crawl_url = f"https://api.zenrows.com/v1/crawls/{response.json()['crawl_id']}"

# wait for the crawl to finish
while requests.get(crawl_url, headers=headers).json()["status"] == "running":
    time.sleep(5)

# download every kept page and parse it with the Step 2 selectors
download = requests.get(f"{crawl_url}/download", headers=headers)
product_data = []
for line in download.text.splitlines():
    soup = BeautifulSoup(json.loads(line)["content"], "html.parser")
    for product in soup.find_all("li", class_="product"):
        product_data.append(
            {
                "Url": product.find("a", class_="woocommerce-LoopProduct-link")["href"],
                "Image": product.find("img", class_="product-image")["src"],
                "Name": product.find("h2", class_="product-name").text,
                "Price": product.find("span", class_="price").text,
            }
        )

# save data to CSV
with open("products.csv", mode="w", newline="", encoding="utf-8") as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=["Url", "Image", "Name", "Price"])
    writer.writeheader()
    writer.writerows(product_data)

print(f"{len(product_data)} products saved to products.csv")
```

Run it, and you'll get the same `products.csv` as your hand-built crawler, with every product on the store:

```bash
188 products saved to products.csv
```

The crawl reached all 12 listing pages in under a minute, with no queue, deduplication, retry, or thread code on your side. Every crawl also reports the pages it fetched, the URLs it kept, the duplicates it removed, and why it stopped. Ask for `"markdown"` instead of `"html"` to get each page ready for an LLM. The [Crawl guide](https://docs.zenrows.com/crawl/setup) covers every option, and the [Crawl announcement](https://www.zenrows.com/blog/introducing-crawl) shows what you can build with it.

When you already have a long list of URLs, such as the ones a crawl returns, [Batch](https://www.zenrows.com/products/batch) runs the whole list as one managed job and hands back each page when it's ready.

You can also run Crawl from the [Python SDK](https://docs.zenrows.com/crawl/sdk/python), with Node.js and Go clients alongside it, from your terminal with the [Zenrows CLI](https://docs.zenrows.com/cli/crawl/introduction), or from an AI agent through the [Zenrows MCP server](https://docs.zenrows.com/mcp/overview), which covers Crawl and Batch as well as scraping, extraction, and browser tools.

### Fetch a Protected Page With Adaptive Stealth Mode
Every page Crawl opens goes through Fetch with [Adaptive Stealth Mode](https://docs.zenrows.com/fetch/features/adaptive-stealth-mode), which picks the fetch settings page by page and adapts as a site's anti-bot measures change. When you need a single page, you can call Fetch directly.

Let's see how Zenrows works by scraping the [Anti-bot Challenge page](https://www.scrapingcourse.com/antibot-challenge), a heavily protected website.

In your Zenrows dashboard, open the [Fetch playground](https://app.zenrows.com/fetch) and paste the target URL in the link box. Adaptive Stealth Mode (`mode: auto`) is on by default. In the Integrate panel, choose API and Python, then copy the generated code into your scraper.

The generated Python code should look like this:

<!-- crawler.py -->
```python
# pip install requests
import requests

url = "https://www.scrapingcourse.com/antibot-challenge"
apikey = "<YOUR_ZENROWS_API_KEY>"
params = {
    "url": url,
    "apikey": apikey,
    "mode": "auto",
}
response = requests.get("https://api.zenrows.com/v1/", params=params)
print(response.text)
```

The above code bypasses the anti-bot challenge and outputs the protected site's full-page HTML:

```html
<html lang="en">
<head>
    <!-- ... -->
    <title>Antibot Challenge - ScrapingCourse.com</title>
    <!-- ... -->
</head>
<body>
    <!-- ... -->
    <h2>
        You bypassed the Antibot challenge! :D
    </h2>
    <!-- other content omitted for brevity -->
</body>
</html>
```

Congratulations!!🎉 You just bypassed an anti-bot measure with Zenrows' Fetch.

## Web Crawling Tools for Python
There are several helpful web crawling tools to make discovering links and visiting pages easier. Here's a list of some of the best Python web crawling tools that can assist you:

1. [**Zenrows Crawl**](https://www.zenrows.com/products/crawl): A web crawler API that follows the links on a site, keeps the URLs you want, drops duplicates, and fetches each page with Adaptive Stealth Mode to get past anti-bot protection. You can use it through the API, the Python, Node.js and Go SDKs, the CLI, and MCP.  
2. [**Scrapy**](https://www.zenrows.com/blog/scrapy-python): One of the most powerful Python crawler frameworks for beginners. It provides a high-level framework for building scalable and efficient crawlers. The [Zenrows Scrapy middleware](https://docs.zenrows.com/integrations/scrapy) routes your spider's requests through Fetch, so the same spider gets past anti-bot protection.  
3. [**Crawlee**](https://www.zenrows.com/blog/crawlee): A web crawling library for Python and Node.js that supports the scraping of static and dynamic websites. Built around a crawling loop, Crawlee automatically discovers and follows the URLs on a web page.
4. [**Selenium**](https://www.zenrows.com/blog/selenium-python-web-scraping): A popular headless browser automation library for web scraping and crawling. It supports JavaScript execution and can interact with web pages in a browser environment like human users would. Zenrows [integrates with Selenium](https://docs.zenrows.com/integrations/selenium) through its residential proxies.
5. [**Crawl4AI**](https://www.zenrows.com/blog/crawl4ai): An open-source Python crawler that converts pages into LLM-ready Markdown for RAG pipelines.

Another important aspect of web crawling you should pay attention to is best practices. You'll learn them in the next section.

## Web Crawling Best Practices in Python
The Python crawling best practices below will help you build a more robust script.

### Crawling JavaScript-Rendered Web Pages in Python
Crawling pages that rely on JavaScript for rendering or data retrieval can be challenging because traditional libraries like Requests and BeautifulSoup can't execute dynamic interactions. Handling them is known as [JavaScript crawling](https://www.zenrows.com/glossary/web-crawling/what-is-javascript-crawling).

The easiest way to [crawl dynamic websites in Python](https://www.zenrows.com/blog/scraping-javascript-rendered-web-pages) is to use headless browser automation tools like Selenium or Playwright. These libraries allow you to control web browsers programmatically and simulate user interactions like clicking, scrolling, and more. They even allow you to [crawl React applications](https://www.zenrows.com/blog/react-crawling).

### Parallel Crawling in Python With Threads
Previously, the crawler handles one page at a time. After sending an HTTP request, it remains idle, waiting for the server's response before proceeding. This approach is less efficient and increases crawling time.

To improve performance, introduce multi-threading to send [parallel requests](https://www.zenrows.com/blog/python-parallel-requests) and process multiple pages concurrently. Each thread fetches and parses a page independently, significantly speeding up the crawl. For thread safety, keep the shared state (the queues, the visited set, and the product list) in one place so no two threads modify it at once.

Fortunately, Python's Queue is thread-safe, meaning multiple threads can read from and write to it without causing race conditions. **A race condition occurs when threads try to modify shared data simultaneously**. Since `Queue` handles synchronization internally, if one thread is accessing a resource, others must wait their turn, ensuring data integrity and preventing conflicts.

Python's [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html) module keeps this simple. A `ThreadPoolExecutor` runs a pool of worker threads: the main loop takes a batch of URLs from the queues, the workers fetch and parse them in parallel, and the main loop queues the new links and stores the products. Only the main thread touches the shared state, so no locks are needed. Each worker gets its own Requests session through the [threading module](https://docs.python.org/3/library/threading.html), since a session isn't guaranteed to be thread-safe. The final crawler code looks like the following after making these changes:

<!-- crawler.py -->
```python
# pip3 install requests beautifulsoup4 tenacity
import requests
from bs4 import BeautifulSoup
import re
import csv
import threading
from concurrent.futures import ThreadPoolExecutor
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError
from queue import Queue

target_url = "https://www.scrapingcourse.com/ecommerce/"

# instantiate the queues
high_priority_queue = Queue()
low_priority_queue = Queue()

# add the start URL to the queue
low_priority_queue.put(target_url)

# create a set to track every URL the crawler has already queued
visited_urls = {target_url}

# set a maximum crawl limit
max_crawl = 20

# specify the number of threads to use
num_workers = 4

# create a regex pattern for product listing page URLs
url_pattern = re.compile(r"/page/\d+/$")

# define a list to collect scraped data
product_data = []

# give each thread its own session
thread_local = threading.local()


def get_session():
    if not hasattr(thread_local, "session"):
        thread_local.session = requests.Session()
    return thread_local.session


# implement a request retry with exponential backoff
@retry(
    stop=stop_after_attempt(4),  # maximum number of attempts
    wait=wait_exponential(multiplier=2, min=2, max=30),  # wait 2s, 4s, then 8s
)
def fetch_url(url):
    response = get_session().get(url)
    response.raise_for_status()
    return response


def crawl_page(current_url):
    # request the target URL and skip it if every retry fails
    try:
        response = fetch_url(current_url)
    except RetryError:
        print(f"Skipped {current_url} after 4 failed attempts")
        return [], []

    # parse the HTML
    soup = BeautifulSoup(response.content, "html.parser")

    # collect all the links as absolute URLs
    links = [
        requests.compat.urljoin(current_url, link_element["href"])
        for link_element in soup.find_all("a", href=True)
    ]

    # extract content only if the current URL matches the regex page pattern
    products = []
    if url_pattern.search(current_url):
        for product in soup.find_all("li", class_="product"):
            products.append(
                {
                    "Url": product.find("a", class_="woocommerce-LoopProduct-link")[
                        "href"
                    ],
                    "Image": product.find("img", class_="product-image")["src"],
                    "Name": product.find("h2", class_="product-name").get_text(),
                    "Price": product.find("span", class_="price").get_text(),
                }
            )

    return links, products


def crawler():
    # set a crawl counter to track the number of pages crawled
    crawl_count = 0

    with ThreadPoolExecutor(max_workers=num_workers) as executor:
        while (
            not high_priority_queue.empty() or not low_priority_queue.empty()
        ) and crawl_count < max_crawl:

            # take up to num_workers URLs, product listing pages first
            batch = []
            while len(batch) < num_workers and crawl_count + len(batch) < max_crawl:
                if not high_priority_queue.empty():
                    batch.append(high_priority_queue.get())
                elif not low_priority_queue.empty():
                    batch.append(low_priority_queue.get())
                else:
                    break

            # update the crawl count
            crawl_count += len(batch)

            # crawl the batch in parallel threads
            for links, products in executor.map(crawl_page, batch):

                # append extracted data
                product_data.extend(products)

                for absolute_url in links:
                    # ensure the crawled link belongs to the target domain and hasn't been queued
                    if (
                        absolute_url.startswith(target_url)
                        and absolute_url not in visited_urls
                    ):
                        visited_urls.add(absolute_url)

                        # prioritize product listing pages
                        if url_pattern.search(absolute_url):
                            high_priority_queue.put(absolute_url)
                        else:
                            low_priority_queue.put(absolute_url)


# execute the crawl
crawler()

# save data to CSV
csv_filename = "products.csv"
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["Url", "Image", "Name", "Price"])
    writer.writeheader()
    writer.writerows(product_data)
```

Run it, and `products.csv` holds the same 188 products as the sequential version.

**Note:** Be careful when running the code, as large numbers in `num_workers` will start many requests at once, increasing the chance of being blocked. However, a high `num_workers` value often reduces execution time.

Threads help because web crawling is I/O-bound. Most of the execution time is spent waiting for the target server to send back HTML, and Python releases the Global Interpreter Lock (GIL) while a thread waits on the network. **More workers speed up the crawl only while the queue holds enough URLs to keep them busy and the server answers as fast as you ask.** Past that point, extra threads wait on the same bottleneck, and a larger pool sends bursts of requests that a site is more likely to block.

Matheus Canhizares, Senior Software Engineer at Zenrows, hints that "*in production, the goal isn't to use the most workers, but the optimal number. For most Python crawlers, the optimal number of workers per CPU core is usually between 3 and 8.*"

Find out why in our tutorial on [web scraping with concurrency in Python](https://www.zenrows.com/blog/speed-up-web-scraping-with-concurrency-in-python).

These performance optimizations are just the beginning. For tech teams building production crawlers, our [web crawling strategies webinar](https://www.zenrows.com/webinars/web-crawling) covers advanced techniques from Zenrows' CTO for making scrapers faster, cutting infrastructure costs, and scaling efficiently.

### Distributed Web Crawling in Python
Distributed crawling involves spreading the crawling job across several servers. While this technique can help you achieve maximum scalability and improve performance, it's a complex process. 

Fortunately, you can achieve distributed web crawling in Python using libraries like [Celery](https://docs.celeryproject.org/en/stable/) or [Redis Queue](https://python-rq.org/).

Our guide to [distributed web crawling](https://www.zenrows.com/blog/distributed-web-crawling) walks through the system and its architecture step by step.

### Store URLs, Status Codes and Pages
Data persistence is helpful for scalability and maintenance. In a real-world crawling scenario, you should store:

* The discovered URLs with their timestamps.  
* Status codes with timestamps to reschedule failed requests.  
* The scraped content.  
* The HTML documents for later processing.

You should export this information to files and/or store it in a database. A site's [sitemap](https://www.zenrows.com/glossary/web-crawling/what-is-a-sitemap) is a useful extra source of URLs to seed the queue with, and the stored URLs let a restarted crawl resume instead of starting over.

### Canonicals to Avoid Duplicate URLs
The current crawling process doesn't account for [canonical links](https://www.zenrows.com/glossary/web-crawling/what-is-a-canonical-url), which website owners often use to indicate that multiple URLs represent the same page.

To avoid redundant crawling, you should check if a canonical URL is in the page's `<link rel= "canonical">` tag. If found, treat it as the official URL and add it to the visited list instead of the original request URL. This prevents duplicate processing when the same page is accessed from different links.

Additionally, a single page can have multiple URLs due to [query parameters](https://www.zenrows.com/glossary/web-crawling/what-are-url-parameters) (e.g., `?ref=123`) or hash fragments (e.g., `#section1`). Without normalization, the crawler may treat these variations as separate pages and crawl them multiple times. While you've used a URL resolver in this tutorial, you can also apply the [`url_query_cleaner`](https://w3lib.readthedocs.io/en/latest/w3lib.html#w3lib.url.url_query_cleaner) to strip unnecessary parameters and standardize URLs before checking for duplicates.

## From a Python Script to a Production Crawler
In this guide, you built a Python web crawler with Requests and Beautiful Soup that discovers a store's product listing pages, extracts each product's name, price, and image, and saves all 188 products to CSV. You then made it production-ready with deduplication, a priority queue, retries, a session, and threads.

**Zenrows Crawl runs that whole discover, follow, and dedupe loop as one API call, and fetches each page through Fetch with Adaptive Stealth Mode to get past anti-bot protection.**

[Start building free](https://app.zenrows.com/register?primitive=crawl) or [speak with sales](https://www.zenrows.com/contact).

## FAQ

### How Do I Create a Web Crawler in Python?

To create a web crawler in Python, first define the initial URL and maintain a set of visited URLs. You can then use libraries such as Requests or [Scrapy](https://www.zenrows.com/blog/scrapy-python) to send HTTP requests and retrieve HTML content. The crawler extracts relevant information from the HTML. Finally, repeat the process by following the links discovered on the pages. To skip writing and hosting the crawler, Zenrows Crawl takes a start URL and returns the URLs it finds on that site in one API call.

### Can Python Be Used for a Web Crawler?

Yes, Python is widely used for web crawling thanks to its rich ecosystem of libraries and tools. It offers libraries like Requests, Beautiful Soup, and Scrapy, simplifying data extraction at scale. Zenrows Crawl also has a Python SDK, so you can run a managed crawl from the same codebase.

### What Is the Best Python Library for Web Crawling?

Requests and Beautiful Soup are the simplest start for small crawls, as this tutorial shows. Scrapy is a full crawling framework with scheduling, pipelines, and middleware, and Crawlee adds browser crawling to the same loop. Zenrows Crawl gives you the crawler as an API, with anti-bot protection handled on every page, so there's no crawler to write or host.

### What Is a Web Crawler Used For?

You can use a web crawler to browse and collect information from sites systematically. They automate fetching web pages and following links to discover new web content. Crawlers are popular for web indexing, content aggregation, and URL discovery.

### How Do I Crawl Data From a Website in Python?

To crawl data from a website in Python, send an HTTP request to the desired URL using a library like Requests. Retrieve the HTML response, analyze the page structure, apply data extraction techniques such as CSS selectors or XPath expressions to find and extract the desired elements and do the parsing with libraries such as BeautifulSoup. With Zenrows Crawl, you send the start URL in one request and read the discovered URLs, and each page's HTML if you ask for it, while the crawl runs.

### What Are the Different Ways to Crawl Web Data in Python?

There are several ways to crawl web data in Python, depending on the target site's complexity and the project's size. Use libraries like Requests and Beautiful Soup for basic crawling and scraping tasks. You might prefer complete crawling frameworks like Scrapy for more advanced functionality and flexibility. Zenrows Crawl turns the whole crawl into a single API call, with Adaptive Stealth Mode handling anti-bot protection on each page.

### Is Web Crawling Legal?

Crawling and scraping of publicly available data is generally legal, and you don't usually need permission to crawl public pages. However, read the site's terms of service, use the collected data ethically, and respect the site's crawling rules, such as those in [robots.txt](https://www.zenrows.com/blog/robots-txt-web-scraping). Abide by local and regional data usage laws and avoid crawling or scraping privately available data, such as those behind a login wall.
