Scraping

How to Make a Web Scraper in Python

Requests and Beautiful Soup, from fetch to CSV file.

TL;DR

  • Fetch, parse, extract. If you're working out how to make a web scraper in Python, the core is a Requests call to fetch the page and Beautiful Soup to parse the HTML and pull out the tags that hold your data.
  • One complete script. The guide builds a single scraper that collects product names and prices from a practice store, handles failed requests, and saves the results to a CSV file, and it shows how to check robots.txt first.
  • Limits and legality. A Ninth Circuit ruling found that scraping public pages likely doesn't violate the main US anti-hacking law, though site terms, copyright, and privacy law still apply. Requests only sees the HTML the server sends, so pages that build their content with JavaScript need a real browser.

Introduction

Working out how to make a web scraper in Python usually starts with something small, like a list of product prices you'd rather have in a spreadsheet than copy by hand. A short script can request the page, pick the names and prices out of the HTML, and write them to a CSV file in a few seconds.

You'll learn how to build that script with Requests and Beautiful Soup, from inspecting the page to saving the data. You'll also handle failed requests, check robots.txt, cover the legal basics of web scraping, and see what to do when a page needs JavaScript to show its content.

What you need before you start

You need Python 3.10 or newer and two libraries that you can install with the following command. Python's Requests library sends the HTTP requests that fetch web pages, and Beautiful Soup parses the HTML and XML documents you get back.

pip install requests beautifulsoup4

If this isn't your only web scraping project on the machine, create a virtual environment first so the packages don't collide. You can check which Python you have with python3 --version, and any text editor and terminal will do.

Requests and Beautiful Soup aren't your only option, and the best Python library depends on the site you're scraping. The comparison of Python web scrapers puts the pair next to Scrapy, Selenium, and Playwright. With almost no setup between you and working code, they're the right pick for a first web scraper and for this Python web scraping tutorial.

Step 1: inspect the page structure with developer tools

Before you write any code, open your target website in a browser, right-click the data you want, and choose "Inspect" to open developer tools. You're looking for two things, which HTML tags and classes wrap each item, and whether the data is already in the raw HTML or only shows up after the page's JavaScript code runs.

The second one is easy to skip and it'll cost you later. Requests only sees the HTML the website's server sends back, so if your data isn't in it, the section on dynamic websites has the fix.

The examples in this guide scrape product names and prices from automationexercise.com/products. It's a practice ecommerce site built for automation testing, so it's a safe target while you're learning web scraping. Inspect its product list and you'll see each product inside a <div class="productinfo text-center">, with the name in a <p> tag and the price in an <h2> tag.

While you're in developer tools, check how the site structure handles long lists. Catalogs and search results pages often split results across URLs like ?page=2, so one response won't give you all the data. The guide on how to scrape data from multiple web pages covers the loop.

One more check before you write the scraper is whether the site wants to be scraped at all. Read its terms of service, then look at its robots.txt file, which lists the paths the owner doesn't want automated tools to visit.

Python's standard library can parse that file for you, and because the practice store doesn't publish one, this example checks python.org instead. Save it as check_robots.py and run it with python3 check_robots.py.

from urllib.robotparser import RobotFileParser

import requests

headers = {"User-Agent": "Mozilla/5.0 (compatible; LearningScraper/1.0)"}

robots = requests.get("https://www.python.org/robots.txt", headers=headers, timeout=10)
robots.raise_for_status()
parser = RobotFileParser()
parser.parse(robots.text.splitlines())

print(parser.can_fetch("LearningScraper", "https://www.python.org/downloads/"))
print(parser.can_fetch("LearningScraper", "https://www.python.org/webstats/"))

python.org disallows /webstats/ for general crawlers, so you'll get True for the first call and False for the second. Before you scrape a real site, swap in its robots.txt and the URL you plan to request.

The example fetches the file with Requests because RobotFileParser.read(), the shorter route, sends Python's default User-Agent. When a server answers that with a 403, the parser treats the whole site as disallowed and you get False for every URL.

Step 2: fetch the HTML content with Requests

Create a file called scraper.py and add this code, which sends a GET request to the target URL and prints the status code so you can see whether you got the page's HTML content back.

import requests

url = "https://automationexercise.com/products"
headers = {"User-Agent": "Mozilla/5.0 (compatible; LearningScraper/1.0)"}

response = requests.get(url, headers=headers, timeout=10)
print(response.status_code)

Run it with python3 scraper.py and you should see 200. Some servers reject a library's default User-Agent, and a slow page can hang a script that has no timeout, so set both from your first request.

Always read the status code before you parse anything, and these three HTTP status codes are the ones to know first.

  • 200. The request succeeded and the response holds the page you asked for.
  • 404. The URL is wrong or the page has moved.
  • 403. The server refused the request, which on a public page usually means it's blocking automated traffic.

Step 3: parse the HTML code with Beautiful Soup

Right now response.text is one long string of HTML code, which is miserable to search by hand. Parsing HTML turns that string into a tree you can query by tag, class, or attribute, and Beautiful Soup does it in one call. Add the following lines to the end of scraper.py to print the page title.

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)

Run it again and you'll see Automation Exercise - All Products, the page's title, which confirms the HTML document parsed.

Step 4: extract the HTML elements you want

You saw in Step 1 that each product sits inside a productinfo block, so add this loop below the parsing lines to go through those blocks and pull the relevant data out of each one.

products = soup.find_all("div", class_="productinfo text-center")

for product in products:
    name = product.find("p").text.strip()
    price = product.find("h2").text.strip()
    print(name, price)

find_all gives you every matching element on the page, while find gives you only the first match inside each block. Run it and you'll get one line per product, starting with Blue Top Rs. 500.

You'll probably want each product's detail page too, from the href attribute on its "View Product" link. That link sits outside the productinfo block, in the card that wraps it, so step up with find_parent before you search.

for product in products:
    card = product.find_parent("div", class_="product-image-wrapper")
    detail_url = card.find("a", href=True)["href"]
    print(detail_url)

You get a relative path like /product_details/1, and Step 6 joins it to the site's address and saves the full URL.

If you already think in CSS selectors, Beautiful Soup's .select() method takes the same syntax, and soup.select("div.productinfo p") returns the same name elements in one selector string.

Step 5: handle errors and scrape responsibly

The script so far assumes every request works, and it'll happily parse an error page when one doesn't. You want it to fail loudly instead, so replace the requests.get line from Step 2 with a try/except block that stops on any failed request.

try:
    response = requests.get(url, headers=headers, timeout=10)
    response.raise_for_status()
except requests.exceptions.RequestException as error:
    print(f"Request failed: {error}")
    raise SystemExit(1)

The line doing the real work is raise_for_status(), which raises an exception for any 4xx or 5xx response. A blocked or missing page now ends the run before your parser ever sees it, and the error message tells you which status code came back.

Error handling protects your script, and pacing your requests protects the site you're scraping. One request is fine, but once your script makes multiple requests in a run, put a time.sleep(1) between them. Dozens of requests a second load the website's server and get you rate-limited or blocked fast.

Step 6: do basic data cleaning and save a CSV file

Printing is fine for checking your selectors, but raw data in a terminal is gone as soon as the script ends. Python's built-in csv module saves it as structured data in a file you can open in a spreadsheet, so replace the print loops from Step 4 with this version.

import csv
from urllib.parse import urljoin

rows = []
for product in products:
    name = product.find("p")
    price = product.find("h2")
    card = product.find_parent("div", class_="product-image-wrapper")
    link = card.find("a", href=True) if card else None
    if name is None or price is None or link is None:
        continue
    rows.append([name.text.strip(), price.text.strip(), urljoin(url, link["href"])])

with open("products.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["product_name", "price", "product_url"])
    writer.writerows(rows)

Three bits of data cleaning happen in that loop before anything is written. .strip() removes the stray whitespace around text pulled out of HTML, and urljoin turns each relative path into a full URL. The None check handles missing values by skipping any card without a name, price, or link, so one odd card can't crash the run.

For data analysis or large datasets, pandas can load the same rows into a DataFrame and export them to JSON or, with openpyxl installed, an Excel file.

Putting it together: the full Python code

The six steps add up to one script you can run from top to bottom.

Six-step flow for making a web scraper in Python, which is to inspect the page, fetch the HTML with Requests, parse it with Beautiful Soup, extract the elements, handle errors, and save a CSV file.

Two things are new, an exit when no products are found and a final line that tells you how many rows were saved.

import csv
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

url = "https://automationexercise.com/products"
headers = {"User-Agent": "Mozilla/5.0 (compatible; LearningScraper/1.0)"}

try:
    response = requests.get(url, headers=headers, timeout=10)
    response.raise_for_status()
except requests.exceptions.RequestException as error:
    print(f"Request failed: {error}")
    raise SystemExit(1)

soup = BeautifulSoup(response.text, "html.parser")
products = soup.find_all("div", class_="productinfo text-center")

rows = []
for product in products:
    name = product.find("p")
    price = product.find("h2")
    card = product.find_parent("div", class_="product-image-wrapper")
    link = card.find("a", href=True) if card else None
    if name is None or price is None or link is None:
        continue
    rows.append([name.text.strip(), price.text.strip(), urljoin(url, link["href"])])

if not rows:
    raise SystemExit("No products found. Check the selector against the live page.")

with open("products.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["product_name", "price", "product_url"])
    writer.writerows(rows)

print(f"Saved {len(rows)} products to products.csv")

Run python3 scraper.py and it tells you how many products it saved, then leaves a products.csv file next to the script with one row per product, and its first lines look like this.

product_name,price,product_url
Blue Top,Rs. 500,https://automationexercise.com/product_details/1
Men Tshirt,Rs. 400,https://automationexercise.com/product_details/2

To point the script at your own target, swap the URL, the find_all selector, and the find calls for the tags that hold your data, and leave the fetch, error handling, and save logic alone. If you're scraping data from a jobs board, for example, that means the tags around each job title and company name.

How to build a reliable web scraper using Python

A script that works today can still break next month without you touching it. Nobody tells you when a site changes its HTML, so write selectors against class names tied to the data itself, like productinfo, and avoid positional guesses like "the third div inside the fourth div." If a redesign breaks your selector anyway, the empty-result check in the full script stops the run before it writes an empty CSV file.

A failed request doesn't always mean the page is gone, either. A server under load can time out or return a 500 that clears up seconds later, so retry a few times with a short pause before you call it a real failure. You can drop this loop in place of the try/except block in your Python scraper.

import time

for attempt in range(3):
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        break
    except requests.exceptions.HTTPError as error:
        if error.response.status_code < 500:
            raise SystemExit(f"Request failed: {error}")
        print(f"Attempt {attempt + 1} failed: {error}")
    except requests.exceptions.RequestException as error:
        print(f"Attempt {attempt + 1} failed: {error}")
    time.sleep(2)
else:
    raise SystemExit("Gave up after 3 attempts")

The loop only retries timeouts, dropped connections, and 5xx server errors. A 4xx response like 403 or 404 won't change on a second try, so the script stops on it straight away. The else on a for loop only runs when the loop finishes without hitting break, which here means all three attempts failed, and it stops the script before the parser runs.

Scraping publicly available pages is common practice, and the best-known US court ruling on it sided with the scraper. In hiQ Labs v. LinkedIn, the Ninth Circuit found that scraping pages anyone can view without logging in likely doesn't violate the Computer Fraud and Abuse Act, and it reached the same conclusion again on remand in 2022.

The ruling is narrower than it sounds. It covers one anti-hacking statute, and the same court noted that claims like breach of contract and copyright infringement can still apply. To keep your web scraping efforts and data collection clear of those, follow the site's robots.txt and the website's terms of service, stay out of pages behind a login, and take extra care with personal information, which privacy laws treat separately.

None of this is legal advice, and the Browserless guide on whether web scraping is legal covers the laws and risks in more detail.

Scraping dynamic websites when Requests and Beautiful Soup aren't enough

Requests and Beautiful Soup are all you need for static pages, where the HTML the server sends already contains the data. You'll outgrow them in two cases, dynamic websites and sites that push back on automated traffic, and in both the same script comes back with nothing.

Why dynamic pages come back empty

Modern websites often send a nearly empty page and fill it in with JavaScript once it loads. Requests can't execute JavaScript, so the dynamic content never appears in response.text, however good your parsing code is.

You can watch it happen on the JavaScript version of the quotes.toscrape.com practice site. This snippet reuses the imports and headers from scraper.py and counts the quote blocks a plain request finds.

js_url = "https://quotes.toscrape.com/js/"

plain = requests.get(js_url, headers=headers, timeout=10)
soup = BeautifulSoup(plain.text, "html.parser")
print(plain.status_code, len(soup.find_all("div", class_="quote")))

You'll get 200 0, a successful request with nothing for the parser to find. The ten quotes are built in the browser by a script, so the HTML data Requests receives has no div.quote elements.

To scrape dynamic pages, you need something that can render JavaScript first. The usual tool is a headless browser, which is a real browser that runs without a window. You can run one yourself, but that means installing a browser plus the browser driver or automation library that controls it, and keeping both updated.

Rendering dynamic sites with Browserless

Browserless runs the headless browser for you and exposes it over HTTP, so your already written code barely changes. Its Content API loads a URL in a real browser, runs the page's scripts, and returns the rendered HTML.

Put your API token in a BROWSERLESS_API_KEY environment variable so it stays out of your code. The call is a POST request with the target URL in a JSON body and the token in the query string, and it's the only part of the previous snippet you need to change.

import os

rendered = requests.post(
    "https://production-sfo.browserless.io/content",
    params={"token": os.environ["BROWSERLESS_API_KEY"]},
    json={"url": js_url, "waitForSelector": {"selector": "div.quote"}},
    timeout=60,
)
rendered.raise_for_status()

soup = BeautifulSoup(rendered.text, "html.parser")
print(len(soup.find_all("div", class_="quote")))

The script now prints 10, and your Beautiful Soup lines didn't change. waitForSelector is what makes that reliable, since it tells Browserless to hold the response until the quotes exist on the page. The docs for using Beautiful Soup with Browserless show more of this pattern.

Two-track comparison of scraping a JavaScript page in Python, where a plain Requests call gets the unrendered HTML and finds 0 quotes, while the Browserless Content API renders the page in a real browser and the same parser finds 10.

If you don't know ahead of time whether a page needs a browser, the Smart Scrape API can make that call. It starts with a plain HTTP fetch and escalates to a proxy, a headless browser, and CAPTCHA solving when the fetch gets blocked or the page needs rendering, then returns JSON with the HTML in a content field.

A page like this one answers a plain request with a 200 and an empty shell, which can pass that first check, so set waitFor to force a browser. Smart Scrape also trims its HTML to the page's main content by default, removing elements like nav, footer, and aside, which can drop parts of the page your selectors target. Set onlyMainContent to False as well to get the full page back.

response = requests.post(
    "https://production-sfo.browserless.io/smart-scrape",
    params={"token": os.environ["BROWSERLESS_API_KEY"]},
    json={
        "url": js_url,
        "formats": ["html"],
        "waitFor": 2000,
        "onlyMainContent": False,
    },
    timeout=120,
)
response.raise_for_status()
result = response.json()
if not result["ok"]:
    raise SystemExit(result["message"])

soup = BeautifulSoup(result["content"], "html.parser")
print(result["strategy"], len(soup.find_all("div", class_="quote")))

This prints browser 10, and the strategy field tells you which approach served the page. Smart Scrape can answer a failed scrape with a 200 and ok set to False, so the snippet checks ok as well as the status code.

The other case is blocking, where sites that notice repeated automated requests respond with rate limits, IP blocks, or a CAPTCHA. Once you've confirmed the site's terms allow what you're collecting, a residential proxy or a CAPTCHA solver can help.

Browserless includes proxy management and CAPTCHA solving in the same service. You can add a residential proxy to a /content call with the proxy=residential query parameter, but /content doesn't solve CAPTCHAs. Smart Scrape and the /unblock API handle CAPTCHAs and bot checks that stop a page from loading, while BrowserQL, the BAP SDK, and Puppeteer or Playwright sessions connected with solveCaptchas=true can solve one inside a page, like a CAPTCHA on a form. For more complex tasks, the walkthrough of modern Python scraping pairs Browserless with AI-assisted selectors.

Conclusion

The habit that saves the most time is checking what the server actually sends before you write a selector. If the data is in the raw HTML, Requests and Beautiful Soup will get it into a CSV file with a short script, with error handling built in.

If the data only shows up after JavaScript runs, keep the parsing code and change how you fetch the page. Browserless loads the page in a real browser and returns the rendered HTML to the same Beautiful Soup calls, which lets you scrape JavaScript-heavy sites without installing or updating a browser yourself, and you can try it on your own target when you sign up for Browserless.

How to make a web scraper in Python FAQs

Is Python good for web scraping?

Python is a strong programming language for scraping, with readable syntax and mature libraries that take you from an empty file to working code quickly. Web scraping with Python also scales with the job, since Requests and Beautiful Soup handle static pages, Scrapy handles large crawls, and Playwright covers pages that need a browser.

Do I need Selenium to build a Python web scraper?

You only need a browser tool like Selenium when the page builds its content with JavaScript. A Selenium script starts with from selenium import webdriver and drives a real browser you install and keep updated, which makes it slower than Requests and Beautiful Soup on static websites that already send their data in the HTML. For JavaScript pages, the Content API approach in this guide returns the rendered HTML without a browser on your machine.

How do I scrape results from a search bar or form?

Submit a search and look at the address bar first. Many search bars send a GET request with the query in the URL, like ?q=python, so you can request that URL with requests.get(url, params={"q": "python"}). If the form sends a POST request, pass the same fields the browser sends as form data with requests.post(url, data={...}), and you can copy the field names from the Network tab in developer tools.

Can Beautiful Soup parse XML files?

Beautiful Soup can parse XML files, but it needs the lxml library for it, so run pip install lxml and pass "xml" as the parser, as in BeautifulSoup(text, "xml"). Without lxml installed, Beautiful Soup raises a FeatureNotFound error. A good XML file to start with is a site's sitemap.xml, when it has one, which lists the pages you might want to scrape.