All work

Entry 02 of 11

Work

Web Scraping

Turn websites into structured data

  • Python
  • Scrapy
  • BeautifulSoup
Read the walkthrough
  1. Scan the listings
  2. Collect names and prices
  3. Save the CSV file

Overview

High‑performance crawlers with anti‑bot evasion and scheduling.

What it covers

  • High-performance crawlers
  • Anti-bot evasion
  • Scheduling
  • Rotating proxies

Demo

Build a first scraper

  1. Start with one public listing page and choose the fields you need. In this walkthrough, each row contains a product name and its price.
  2. Fetch the page with Requests in Python. Use BeautifulSoup to find the HTML element that repeats for each product, then read the name and price inside that element.
  3. Write one row per product to a CSV file and check a few rows against the page. Once they match, use Scrapy to follow the next listing page and apply the same extraction.

Export a public Shopify product catalog to CSV

On a Shopify store you own or have permission to read, this Python example exports one row per published product. Each row contains the title, handle, lowest variant price and currency returned by the Storefront API.

  1. Save the code as export_catalog.py. For a store named example-shop.myshopify.com, run python3 export_catalog.py example-shop products.csv. Substitute your store’s name. The script uses Python 3’s standard library.
  2. The read-only Storefront GraphQL query requests 50 products per page. It sends the last page’s endCursor as after until hasNextPage is false, then replaces the CSV. If the store denies access, confirm publication and access with its owner. For HTTP 429, wait for Retry-After when provided before retrying.
  3. Compare a few rows with the storefront in the same market. For products with several variants, min_price records the lowest variant price. A store-wide export including drafts requires a merchant-authorized GraphQL Admin API app with read_products.
export_catalog.py
import argparse
import csv
import json
import re
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.request import Request, urlopen

QUERY = """
query Catalog($after: String) {
  products(first: 50, after: $after, sortKey: ID) {
    nodes { title handle priceRange { minVariantPrice { amount currencyCode } } }
    pageInfo { hasNextPage endCursor }
  }
}
"""

def export_catalog(shop, output):
    if not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", shop):
        raise ValueError("Use the shop name before .myshopify.com")
    url = f"https://{shop}.myshopify.com/api/2026-10/graphql.json"
    cursor = None
    with TemporaryDirectory(dir=output.parent) as directory:
        draft = Path(directory) / "catalog.csv"
        with draft.open("w", encoding="utf-8", newline="") as file:
            writer = csv.writer(file)
            writer.writerow(["title", "handle", "min_price", "currency"])
            while True:
                body = json.dumps({"query": QUERY, "variables": {"after": cursor}})
                request = Request(url, data=body.encode("utf-8"),
                                  headers={"Content-Type": "application/json"})
                with urlopen(request, timeout=20) as response:
                    result = json.load(response)
                if result.get("errors"):
                    raise RuntimeError(result["errors"][0]["message"])
                products = result["data"]["products"]
                for product in products["nodes"]:
                    price = product["priceRange"]["minVariantPrice"]
                    writer.writerow([product["title"], product["handle"],
                                     price["amount"], price["currencyCode"]])
                page = products["pageInfo"]
                if not page["hasNextPage"]:
                    break
                if not page["endCursor"] or page["endCursor"] == cursor:
                    raise RuntimeError("Shopify returned no new page cursor")
                cursor = page["endCursor"]
        draft.replace(output)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Export published Shopify products")
    parser.add_argument("shop", help="Shop name before .myshopify.com")
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    export_catalog(args.shop, args.output)

Documentation