ScrapeStack

All guides

INDEPENDENT WEB SCRAPING GUIDE

How to Scrape a Website: Python Example to CSV

Learn how to scrape a website in six steps, run a no-dependency Python example, export links to CSV and fix common scraping problems.

By Sufyan Rasheed · Reviewed October 20, 2026

The short answer

To scrape a website, choose the fields you need, check that collection is permitted, fetch the page HTML, extract matching elements, validate the records and export them to CSV. Start with one page before adding pagination or scheduling.

Jump to the runnable Python example

Choose the right way to scrape a site

What you needStart withWatch for
A few recordsA manual copy or the site's exportCopying errors and missing context
Data already offered through an APIThe site's documented APIAuthentication, fields and usage limits
Links or text in the initial HTMLA Python HTTP request and HTML parserRelative URLs and changes to page markup
Content loaded after JavaScript runsA documented data endpoint or authorized browser automationHTML-only requests do not execute JavaScript
A managed fetching serviceA scraping APIPlan limits and the separate work of parsing returned HTML

How to scrape a website in six steps

1. Decide what one output row represents

For this tutorial, one row is one link: its visible text and destination URL. For a product catalog, one row might instead contain a product title, price, currency and source URL. Write the column names before collecting data so you know what a complete record looks like.

2. Check the source and collection rules

Prefer an official export or API if it provides the fields you need. Check the site's terms, robots.txt and any permission or data-use requirements. A public page is not automatic permission to collect personal information. This example makes one request; do not extend it into bulk collection without reviewing the source's rules and limits.

3. Inspect the actual HTML

Use your browser's View Source or developer tools to find the element containing the data. A link usually appears as <a href="/about/">About</a>. If your value is visible in the browser but absent from the initial HTML, it may arrive later through JavaScript. That is a different collection method, not a reason to keep repeating the same request.

4. Fetch and parse one page

The script below uses only Python's standard library. It reads an HTML response, extracts link text and addresses, resolves relative addresses and ignores non-web schemes such as mailto. It does not follow the extracted links, execute JavaScript, sign in or bypass access controls.

Python web scraping example: links to CSV

Install Python 3, save this as scrape_links.py, then run the command below. No pip packages or scraping API account are required. Use example.com for the first small run or substitute a page you own or have permission to collect.

python scrape_links.py https://example.com/
"""Extract links from one permitted HTML page into a CSV; Python 3 only."""
import csv
import sys
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, urlopen

class LinkParser(HTMLParser):
    def __init__(self, base_url):
        super().__init__(convert_charrefs=True)
        self.base_url, self.rows = base_url, []
        self.href, self.label = None, []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            self.href = dict(attrs).get("href")
            self.label = []

    def handle_data(self, data):
        if self.href is not None:
            self.label.append(data)

    def handle_endtag(self, tag):
        if tag == "a" and self.href is not None:
            url = urljoin(self.base_url, self.href)
            text = " ".join("".join(self.label).split())
            if urlsplit(url).scheme in {"http", "https"}:
                self.rows.append((text, url))
            self.href, self.label = None, []

def csv_safe(value):
    # Keep spreadsheet software from interpreting extracted text as a formula.
    return "'" + value if value.lstrip().startswith(("=", "+", "-", "@")) else value

def scrape(url, output="links.csv"):
    if urlsplit(url).scheme not in {"http", "https"}:
        raise ValueError("Use an HTTP or HTTPS page you are permitted to collect.")
    request = Request(url, headers={"User-Agent": "ScrapeStackGuide/1.0 (+https://scrapestack.dev/about/)"})
    with urlopen(request, timeout=20) as response:
        if response.headers.get_content_type() != "text/html":
            raise ValueError("This example expects an HTML response.")
        parser = LinkParser(response.url)
        parser.feed(response.read().decode(response.headers.get_content_charset() or "utf-8", errors="replace"))
        parser.close()
    rows = list(dict.fromkeys(parser.rows))
    with open(output, "w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["text", "url"])
        writer.writerows((csv_safe(text), link) for text, link in rows)
    return len(rows)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python scrape_links.py https://example.com/")
    print(f"Saved {scrape(sys.argv[1])} unique links to links.csv")

5. Inspect the exported file

The command writes links.csv in your current working folder. Its first row is text,url; the following rows contain the links found in that page's HTML. The program removes exact duplicate text-and-URL pairs. Different labels pointing to the same URL remain separate records. Open a few destinations and confirm the labels match the source.

For example, the HTML <a href="/about/">About us</a> on https://example.com/ becomes this record:

text,url
About us,https://example.com/about/

CSV quoting is handled by Python. Spreadsheet formula-like labels get an apostrophe prefix so they remain text. For extra trimming and deduplication, paste a small export into the free browser CSV cleaner; it does not upload your pasted data.

6. Add scale only after validation

If you later need multiple pages, first define which URLs belong in scope, how much delay each source needs, when to stop and how to record failures. Save a source URL and collection time with each record. Keep a small known HTML sample to check your parser when the website changes.

Why does my website scraper return no data?

Common website scraping questions

Can I scrape a website for free?

You can run this Python example locally without paying for an API. Hosting, browser automation and managed services may have separate costs. A service's free plan is not the same as unlimited collection; see the scrapestack free-plan guide for that specific product.

How do I scrape a website without coding?

Check for a built-in CSV download or table export first. For a few rows, manual collection may be enough. A no-code scraper still needs a defined field map and a review of the result. Our CSV cleaner cleans existing data; it does not fetch website URLs.

Is scraping the same as using the scrapestack API?

No. Website scraping is a task; scrapestack.com offers one managed API for fetching page content. Parsing fields and validating exports remain separate steps. Read our independent scrapestack API quickstart if you are evaluating that service.

Sources and next steps

The example uses Python's documented HTTP request tools, HTML parser and CSV writer. For field planning, continue with the Python extraction checklist; for output design, read website data to CSV.