Your code snippet generally looks good, but there are a few improvements and corrections that can be made for better clarity and performance. I'll also correct some issues that may arise:
- Ensure that the
return statement in your parseCurrency function properly handles cases where parseFloat fails.
- The summation in the console log should correctly access the price properties of the array items.
- You might want to use
Promise.all if you plan to use multiple asynchronous operations for better performance.
- Make sure to handle the case when there might be no prices available, as this could lead to errors.
Here's a revised version of your code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: "new" });
const page = await browser.newPage();
const item = "your_item_here"; // Replace with the appropriate item
await page.goto(`https://www.ebay.fr/sch/i.html?_nkw=${encodeURIComponent(item)}&_ipg=240`);
const itemInfoBased = await page.evaluate(() => {
function parseCurrency(str) {
const cleanedStr = str.replace(/\s*EUR$/, '').trim();
const normalizedStr = cleanedStr.replace(/\u00A0/g, '');
const numberStr = normalizedStr.replace(',', '.');
const amount = parseFloat(numberStr);
return isNaN(amount) ? null : amount; // Return null if parsing fails
}
const elements = document.querySelectorAll(".s-item__info");
const arr = [];
elements.forEach(e => {
const priceItem = parseCurrency(e.querySelector(".s-item__price")?.textContent);
if (priceItem !== null) {
arr.push({
price: priceItem,
});
}
});
return arr; // Return the array instead of a JSON string
});
console.log(itemInfoBased);
const total = itemInfoBased.reduce((sum, current) => sum + current.price, 0); // Initialize sum to 0
console.log("Total price:", total);
await browser.close();
})();
Key Changes:
- Error Handling: In
parseCurrency, it now checks if parseFloat results in NaN, returning null in that case.
- Returning Raw Array: The
itemInfoBased now returns the raw array instead of a JSON string, simplifying the JSON.parse requirement.
- Optional Chaining (
?.): This helps avoid errors if .textContent is accessed on an undefined element.
- Total Calculation: Changed how the total price is calculated by initializing the accumulator to
0.
Make sure to replace "your_item_here" with the actual item you're searching for. Also, ensure you have proper error handling if you plan to run this code in a production environment.