Planning robust price scraper
Detailed heuristics for identifying prices via DOM scanning, font size, proximity to buy buttons, and filtering visible elements were laid out to avoid brittle selectors; next step is implementing a Node.js Playwright script that loads pages, evaluates prices with these heuristics, and outputs parsed prices for comparison.
Below is a self‑contained Playwright script that will open product pages in a headless browser, scan the live DOM for currency symbols, and use simple heuristics (font size, non‑strikethrough, proximity to “Add to Cart”/“Buy” buttons) to pick the most likely price.
Prerequisites: Node.js ≥14, npm install playwright
// price-scraper.js
import { chromium } from 'playwright';
const CURRENCY_CHARS = ['$', '£', '€', '¥', '₹', '₽', '₩', '₺', 'R', 'C$', 'A$', 'Rs'];
async function scrapePrice(url, browser) {
const page = await browser.newPage({
viewport: { width: 1280, height: 900 },
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'
});
await page.goto(url, { waitUntil: 'networkidle' });
// Give late-loading widgets a moment to settle
await page.waitForTimeout(1000);
const result = await page.evaluate((currencyChars) => {
// Heuristic helpers
const currencyRegex = new RegExp(
'(' + currencyChars.map((c) => c.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|') + ')\\s*\\d',
'i'
);
const isVisible = (el) => {
const rect = el.getBoundingClientRect();
const style = getComputedStyle(el);
const hasSize = rect.width > 0 && rect.height > 0;
const visibleDisplay = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
return hasSize && visibleDisplay;
};
const findBuyButtons = () => {
const terms = /(add to cart|add to bag|add to basket|buy now|buy|checkout|purchase|trolley)/i;
return Array.from(document.querySelectorAll('button, a, input[type=submit]')).filter((el) => {
return isVisible(el) && terms.test(el.innerText || el.value || '');
});
};
const parsePriceNumber = (text) => {
const clean = text.replace(/[^0-9.,]/g, ' ').replace(/\s+/g, ' ').trim();
// Try to handle commas as thousand separators vs decimals
// e.g. "1,299.99" or "1.299,99"
let num = NaN;
if (clean.includes(',') && clean.includes('.')) {
// decide which is decimal separator by last occurrence
const lastComma = clean.lastIndexOf(',');
const lastDot = clean.lastIndexOf('.');
if (lastComma > lastDot) {
// comma as decimal separator
num = parseFloat(clean.replace(/\./g, '').replace(',', '.'));
} else {
// dot as decimal separator
num = parseFloat(clean.replace(/,/g, ''));
}
} else if (clean.includes(',')) {
// single separator: assume comma is decimal if there's only one group after
const parts = clean.split(',');
if (parts[parts.length - 1].length === 2) {
num = parseFloat(clean.replace('.', '').replace(',', '.'));
} else {
num = parseFloat(clean.replace(/,/g, ''));
}
} else {
num = parseFloat(clean);
}
return num;
};
const buyButtons = findBuyButtons();
const priceCandidates = [];
const allElements = Array.from(document.querySelectorAll('body *'));
for (const el of allElements) {
if (!isVisible(el)) continue;
const text = (el.innerText || '').trim();
if (!text) continue;
if (!currencyRegex.test(text)) continue;
// Eliminate obviously too long blobs of text
if (text.length > 100) continue;
const style = getComputedStyle(el);
const fontSize = parseFloat(style.fontSize) || 0;
const isLineThrough = style.textDecoration.includes('line-through');
const rect = el.getBoundingClientRect();
// Distance to nearest buy button (center-to-center)
let minDist = Infinity;
for (const btn of buyButtons) {
const bRect = btn.getBoundingClientRect();
const dx = bRect.left + bRect.width / 2 - (rect.left + rect.width / 2);
const dy = bRect.top + bRect.height / 2 - (rect.top + rect.height / 2);
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist) minDist = dist;
}
// If no buy buttons found, distance heuristic won't apply
if (minDist === Infinity) minDist = 500; // arbitrary fallback
// Penalty for strikethrough (likely old price)
const strikePenalty = isLineThrough ? 0.25 : 1.0;
// Score: larger font, closer to buy button => higher
const score = (fontSize * strikePenalty) / (1 + minDist / 200);
priceCandidates.push({
text,
fontSize,
minDist,
isLineThrough,
score,
value: parsePriceNumber(text)
});
}
// Also consider schema/meta hints
const metaCandidates = [];
const metaSelectors = [
'meta[itemprop=price]',
'meta[property="product:price:amount"]',
'meta[name="twitter:data1"]',
'meta[name="og:price:amount"]'
];
metaSelectors.forEach((sel) => {
document.querySelectorAll(sel).forEach((m) => {
const content = m.getAttribute('content') || '';
if (!content) return;
const val = parseFloat(content);
if (!isNaN(val)) {
metaCandidates.push({
text: content,
value: val,
score: 0.5, // medium confidence
fontSize: 0,
minDist: 9999,
isLineThrough: false
});
}
});
});
const candidates = priceCandidates.concat(metaCandidates);
if (!candidates.length) return null;
// Pick the candidate with the highest score; tie-breaker on value existence
candidates.sort((a, b) => b.score - a.score || (isNaN(a.value) ? -1 : 1));
const best = candidates[0];
return {
priceText: best.text,
priceValue: best.value,
score: best.score,
minDist: best.minDist,
fontSize: best.fontSize,
isLineThrough: best.isLineThrough
};
}, CURRENCY_CHARS);
await page.close();
return {
url,
...result
};
}
async function main(urls) {
const browser = await chromium.launch({ headless: true });
try {
const results = [];
for (const url of urls) {
try {
console.log(`Scraping: ${url}`);
const res = await scrapePrice(url, browser);
results.push(res);
} catch (err) {
console.error(`Failed to scrape ${url}:`, err.message);
}
}
console.log('\nResults:\n', JSON.stringify(results, null, 2));
} finally {
await browser.close();
}
}
// Example usage: node price-scraper.js https://example.com/product1 https://example.com/product2
if (require.main === module) {
const urls = process.argv.slice(2);
if (!urls.length) {
console.error('Usage: node price-scraper.js <url1> <url2> ...');
process.exit(1);
}
main(urls);
}
How it works
- Loads each product page in a headless Chromium instance and waits for network idle.
- In the page context, walks the DOM to find visible elements whose text contains a currency symbol.
- For each candidate it gathers:
- Font size (larger fonts favored)
- Whether it’s struck through (old price penalized)
- Distance to the nearest “Add to Cart”/“Buy” button (closer is favored)
- Optionally considers meta/schema price hints as fallback.
- Scores each candidate and returns the highest‑scoring one.
You can adjust the heuristics (keywords for buy buttons, currency symbols, scoring formula) to fit your use case or add additional signals such as color, boldness, or JSON‑LD parsing for even more robustness.