The best sources for product data are official APIs and feeds, then structured data embedded in the page. Sometimes neither exists and the only thing left is the markup a person sees. Parsing that is easy to get working and hard to keep correct. The aim is not a selector that never breaks; it is a parser that, when the page changes, tells you, instead of quietly returning the price of something else.
Key takeaways
- Check for an API, a feed and embedded JSON first. HTML-only parsing is the last resort, not the default.
- Anchor to something that identifies the product, then search only inside its container.
- Prefer explicit contracts and visible labels over generated class names and positional paths.
- Validate cardinality: one product, one current price. Anything else is an error, not a choice.
- A loud failure costs a fix. A silent wrong value costs a decision. Design for the first.
First, make sure HTML really is all there is
Look at the page source before writing a selector. Many product pages carry JSON-LD with Product and Offer data, or embed the application state as JSON; we mapped where five large US retailers keep it in where e-commerce data actually lives. Check whether the site offers an official API or feed for your use case, as we discuss in web scraping vs official APIs. Only when none of those exist does the rest of this article apply.
The problem: a page full of prices
A product page rarely contains one price. Promotions in the header, carousels of other products, struck-through “was” prices, multi-buy offers and financing terms all put dollar amounts on the page. The extraction question is never “find the price” but “find this product’s current price, and be sure there is exactly one”.
Six dollar amounts, one current price
How scoping to the product container narrows the candidates on a test page
Anchors, in our order of preference
Every selector rests on some feature of the page staying the same. Some features are more deliberate than others.
| Anchor | Example | Why we rank it here |
|---|---|---|
| Structured data in the page | itemprop="price", JSON-LD | Published on purpose for machines, often for search engines |
| Explicit test or data attributes | data-testid="product-price" | Put there on purpose, though for the site’s own tests, not for you |
| Visible text and roles | The one h1; labels such as “Was” and “Now” | Changing them changes what shoppers see, so they change less casually |
| Readable class names | .price, .product-title | Convenient, but a restyle can rename or reuse them |
| Generated class names | .c-77qd, .css-1x9k2 | Often regenerated when the site is rebuilt |
| Positional paths | /html/body/main/div[1]/div[1]/span[1] | Depend on everything above the element staying put |
This order is our judgment, not a measurement. We know of no reliable public data on how long selectors of each kind survive.
The ranking echoes Playwright’s guidance for test authors, which recommends role, text and test-id locators and says that “CSS and XPath are not recommended as the DOM can often change leading to non resilient tests” (Playwright docs). The difference for a data team is that you don’t control the page. Test ids can disappear, and labels can be reworded. No anchor is permanent, which is why validation matters more than the choice of selector.
A small test you can rerun
To make the trade-offs concrete, we wrote a synthetic product page and seven variations of it, each mimicking a change real pages go through: an extra wrapper element, regenerated class names, a sale with a struck-through price, a carousel moved above the product, an out-of-stock state, a four-digit price and a multi-buy offer. Then we ran four strategies against all eight:
- Absolute XPath, as copied from browser developer tools on the original page.
- Class-name CSS,
.pdp .price-block .price, written against the original page. - First $ amount in the page body, the shortcut many quick scripts take.
- Anchored and validated: find the single product heading, search only inside its container, skip prices that are struck through or labelled “was”, and require exactly one candidate.
| Fixture | Absolute XPath | Class-name CSS | First $ amount | Anchored and validated |
|---|---|---|---|---|
| Baseline | ✓ | ✓ | ✓ | ✓ |
| Extra wrapper added | error | ✓ | ✓ | ✓ |
| Class names regenerated | ✓ | error | ✓ | ✓ |
| Sale price with was price | ✓ | wrong: $119.99 | wrong: $119.99 | ✓ |
| Carousel moved above product | ✓ | ✓ | wrong: $14.99 | ✓ |
| Out of stock, no price | error | error | wrong: $24.99 | ✓ (no price) |
| Price over $1,000 | ✓ | ✓ | ✓ | ✓ |
| Multi-buy offer added | ✓ | ✓ | ✓ | error |
Expected value for every fixture is $89.99, except the out-of-stock page (no price) and the four-digit page ($1,299.00). Run by JsonEngine on October 30, 2026.
What fails loudly and what fails quietly
Four extraction strategies on eight synthetic product-page fixtures
Data behind the chart
| Strategy | Correct | Loud failure | Silent wrong value |
|---|---|---|---|
| Absolute XPath | 6 | 2 | 0 |
| Class-name CSS | 5 | 2 | 1 |
| First $ amount | 5 | 0 | 3 |
| Anchored and validated | 7 | 1 | 0 |
Read this for the pattern, not the scores. We wrote the fourth strategy knowing what the fixtures contain, so its result proves little on its own; a different set of fixtures would break it somewhere. Two things hold more generally. The “first dollar amount” shortcut never raised an error and was wrong three times out of eight, which is the worst combination. And the anchored strategy’s one failure was the useful kind: faced with a multi-buy offer it had no rule for, it stopped and reported two candidates rather than picking one.
The anchored approach in code
Python (lxml)import re
from decimal import Decimal
MONEY = re.compile(r"\$\s?(\d{1,3}(?:,\d{3})*(?:\.\d{2})?|\d+(?:\.\d{2})?)")
WAS = re.compile(r"\b(was|regular|list|compare at)\b", re.I)
UNAVAILABLE = re.compile(r"unavailable|out of stock|sold out", re.I)
class Ambiguous(Exception):
pass
def current_price(doc):
h1s = doc.xpath("//h1")
if len(h1s) != 1:
raise Ambiguous("expected one product heading, found %d" % len(h1s))
box = h1s[0].getparent() # the product container
cands = []
for el in box.iter():
if el.tag in ("s", "del") or WAS.search(el.text_content()[:20]):
continue # struck-through or labelled 'was'
own = (el.text or "") + "".join((c.tail or "") for c in el)
for m in MONEY.finditer(own):
cands.append(Decimal(m.group(1).replace(",", "")))
cands = sorted(set(cands))
if len(cands) == 1:
return cands[0]
if not cands and UNAVAILABLE.search(box.text_content()):
return None # no price, and the page says why
raise Ambiguous("found %d price candidates: %s" % (len(cands), cands)) It is deliberately small. On a real site you choose the container once per site and test it, rather than assuming it is the heading’s parent, and you add the labels that site uses. Three habits carry over to any parser: parse money with Decimal, never a float; treat “no price” as a state with a reason, not an empty string; and raise on ambiguity.
Validation rules worth writing down
- One product. Exactly one product heading or identifier per product page.
- One current price, or an explicit unavailable state. Two candidates is an error.
- Identity check. The SKU or identifier on the page matches the one you expected from the URL or listing.
- Plausibility. Flag a price that moves more than a threshold you set since the last observation, for a person to look at.
- Evidence. Store the text the value came from and which rule matched, so a reviewer can see why.
Watching for layout drift
Parsers rarely break on a schedule. Track, per site and per run, the share of pages where each field was filled, the share that raised ambiguity errors and the share marked unavailable. A step change in any of them usually means the page changed, not the market. Keep a set of saved pages, where you are permitted to store them, as fixtures, and rerun them whenever you change a parser. A suite like the one above takes minutes to run and catches the quiet failures that production data won’t show you.
Quick answers
How do you scrape a website that has no API?
First check the page source for structured data such as JSON-LD or embedded JSON. If there is none, parse the HTML: anchor to something that identifies the product, search only inside its container, and validate every value.
Are CSS selectors or XPath better for scraping?
Neither is reliable by itself. What matters more is what the selector anchors to and whether you validate the result. Positional paths and generated class names tend to be the most fragile anchors.
Why does my scraper return the wrong price?
Usually because the page contains several prices, such as promotions, carousels, was prices or multi-buy offers, and the selector picked the wrong one. Scope to the product container and require exactly one current price.
How do I know when a scraper breaks?
Track per-field fill rates and ambiguity errors per site and run. A sudden change usually means the page layout changed. Keep saved pages as regression fixtures and rerun them after every parser change.
Need parsed, validated product data?
We maintain parsers and validation rules per site, so you get records, not selectors. See custom datasets or ask about a source.
