All articles4 min read
Data collection

Shopify scraping with Python: products, variants and availability

Build a variant-level product export from a permitted storefront data source.

Generated editorial photograph illustrating build a permitted product-data workflow and evaluate its fetching infrastructure.

Shopify scraping with Python starts with a permitted data source and the product model you need to preserve. A product can have several variants, with different prices and availability. Flattening the first visible price into one row per product can lose the detail your dataset was meant to capture.

Choose a permitted collection path

For a store you operate or are authorized to integrate with, inspect the current Storefront API and the access available to your application. Check the API version, authentication and scopes before sending a query. Do not assume that every storefront exposes the same unauthenticated endpoint or fields.

For permitted collection from public pages, inspect the response and rendered page before choosing an extraction method. Validate any embedded structured data against the actual offer. If access is denied, keep the denial explicit; do not treat it as an instruction to bypass the restriction.

This guide's Python example parses a saved, authorized Storefront-style response. It does not retrieve a live store or claim that Crawlhub supplies a dedicated Shopify endpoint. A network client and its authorization remain separate from this parsing step.

Keep product identity and variant identity

Store the product identifier and each variant identifier separately. Preserve option selections, currency and the price associated with that variant. A title alone is a weak key when a store changes its naming or sells similar items.

An API field describing whether a variant can be sold is not a universal warehouse stock count. Preserve its meaning. Keep missing or unusable availability as unknown instead of converting it to false. Check related fields and the current application contract when a use case needs a more precise inventory interpretation.

Retain the observation time and the store or market context used to collect the response. Prices and offers from different contexts should not be silently merged.

Parse a defined response shape

The helper below expects data.products.nodes, with a variants.nodes connection and pagination metadata for both levels. Those fields must be included in the authorized query. A response containing GraphQL errors is rejected here, even if it also contains partial data.

def variant_records(payload):
    def has_more(connection):
        value = connection["pageInfo"]["hasNextPage"]
        if type(value) is not bool:
            raise ValueError("invalid pagination state")
        return value

    if payload.get("errors"):
        raise ValueError("response contains errors")
    products = payload["data"]["products"]
    complete = not has_more(products)
    rows = []
    seen = set()
    for product in products["nodes"]:
        variants = product["variants"]
        more_variants = has_more(variants)
        complete = complete and not more_variants
        for variant in variants["nodes"]:
            key = variant["id"]
            if not key or key in seen:
                raise ValueError("missing or duplicate variant id")
            seen.add(key)
            value = variant.get("availableForSale")
            rows.append({
                "product_id": product["id"],
                "variant_id": key,
                "options": variant["selectedOptions"],
                "price": variant["price"],
                "available_for_sale": value if type(value) is bool else None
            })
    return {"records": rows, "complete": complete}

The price object remains unchanged, retaining its amount and currency. Validate it before numeric comparisons using your price-normalization contract. This helper is a parser for a known export shape, not a general-purpose validator for untrusted arbitrary JSON.

A valid empty products connection can yield an empty record list. Missing required connection fields should fail rather than be interpreted as an empty store. The separate complete flag becomes false if either level reports another page. It does not fetch those pages for you.

Track both levels of pagination

A page of products and a page of variants are separate boundaries. Follow the documented cursors for each connection your query needs. Saving the first page of variants for every product does not establish a complete catalog.

Record cursors and checkpoints privately when resuming an authorized job. Detect repeated cursors and duplicate identifiers instead of looping indefinitely. Keep a failed request separate from a successful page with no records. The existing pagination guide describes the stopping conditions to make explicit.

Test the output before using it

Use controlled examples with two variants, different option values, true and false sale availability, and a missing availability field. Include an empty response, a partial response with errors and a variant connection that has another page.

Compare accepted records with permitted source observations. Verify that prices describe the intended variant and that a data gap has not become a sold-out label. Keep the original value or evidence needed to investigate a mismatch.

Scale the collection method you verified

Increase volume only after the permitted access path, record contract and pagination behavior are established. Use bounded requests, deadlines and retries. Do not assume that a proxy changes an API's access requirements or removes its limits.

If you need to evaluate the fetching layer, review Crawlhub's Web Scraping API and residential proxies against the current account documentation. Start with a small test using an authorized source, and keep collection evidence separate from the exported dataset.

Contact us

Tell us what you want to collect.

See our Privacy Notice for how we handle your message.

Your message is sent to hello@crawlhub.ai. Please do not include passwords or API keys.