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.
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 exampleChoose the right way to scrape a site
| What you need | Start with | Watch for |
|---|---|---|
| A few records | A manual copy or the site's export | Copying errors and missing context |
| Data already offered through an API | The site's documented API | Authentication, fields and usage limits |
| Links or text in the initial HTML | A Python HTTP request and HTML parser | Relative URLs and changes to page markup |
| Content loaded after JavaScript runs | A documented data endpoint or authorized browser automation | HTML-only requests do not execute JavaScript |
| A managed fetching service | A scraping API | Plan 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?
- Empty CSV: the response may have no links, or JavaScript may load them later. Compare the downloaded HTML with what you see in the browser.
- HTTP 403: access was refused. Check permissions and the source's documented access method rather than trying to force the request through.
- HTTP 429: stop and respect the source's retry guidance; reduce request frequency.
- Wrong characters: check the page's character encoding and the original response before cleaning text.
- Missing fields: inspect the selector or markup. This example collects links, not every table, product or image on a page.
- CSV import problems: read the CSV import checklist and keep identifiers as text.
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.