From f61c718b61ccdb56705d662c1e3792832dc6c1b2 Mon Sep 17 00:00:00 2001 From: Arnav Jagetia Date: Mon, 26 Jan 2026 14:08:47 -0500 Subject: [PATCH] Fixed price extraction error handling and add null checks --- lib/Amazon.js | 12 ++++++++---- lib/constant.js | 16 +++++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/Amazon.js b/lib/Amazon.js index 3b37774..bcdeb30 100644 --- a/lib/Amazon.js +++ b/lib/Amazon.js @@ -1175,10 +1175,14 @@ class AmazonScraper { ? $($(`span.reviewCountTextLinkedHistogram.noUnderline`)[0]).text().split(/\s/g)[0] : 0; - output.price.current_price = $(`span.a-price.priceToPay`)[0] - ? this.geo.price_format($($(`span.a-price.priceToPay`)[0].children[0]).text()) - : 0; - if (!output.current_price) { + try { + output.price.current_price = $(`span.a-price.priceToPay`)[0] + ? this.geo.price_format($($(`span.a-price.priceToPay`)[0].children[0]).text()) + : 0; + } catch { + output.price.current_price = 0; + } + if (!output.price.current_price || output.price.current_price === 0) { try { output.price.current_price = this.geo.price_format($($(`span.a-price.apexPriceToPay`)[0].children[0]).text()); } catch { diff --git a/lib/constant.js b/lib/constant.js index 6e8ade6..9f482ea 100755 --- a/lib/constant.js +++ b/lib/constant.js @@ -56,11 +56,21 @@ module.exports = { return ''; }, price_format: (price) => { - const formatedPrice = price.match(/.*\$([0-9.]+)/); + // multiple regex patterns for diffrent price formats + const patterns = [ + /\$\s*([0-9,]+\.?[0-9]*)/, // $123.45 or $ 123.45 or $1,234.56 + /USD\s*([0-9,]+\.?[0-9]*)/, // USD 123.45 + /([0-9,]+\.?[0-9]*)/, // just numers (fallback) + ]; - if (formatedPrice.length > 0) { - return parseFloat(formatedPrice[1]); + for (const pattern of patterns) { + const match = price.match(pattern); + if (match && match[1]) { + // remove commas from number strs + return parseFloat(match[1].replace(/,/g, '')); + } } + return 0.0; }, product_information: {