使用Puppeteer筛选折扣大于指定阈值的商品链接问题求助
问题核心原因
你的代码存在两个核心逻辑错误:
- 直接对整个折扣数组和折扣阈值做比较,数组无法直接和单个数值判断大小
- 折扣数据和阈值都使用了字符串类型,比较时会按字符串ASCII规则匹配,不符合数值比较的需求
你获取到的折扣数组和商品链接数组是同索引一一对应的,只需遍历索引,筛选出符合折扣条件的位置对应的链接即可。
修正后的完整代码
const puppeteer = require('puppeteer') // 阈值改为数字类型,方便后续数值比较 const minDiscount = 20 async function getLinks(){ const browser = await puppeteer.launch({headless: false, defaultViewport: null}); const page = await browser.newPage(); const url = 'https://www.chainreactioncycles.com/mtb/mountain-bikes' await page.goto(url) // 先等待元素加载完成,再提取数据 await page.waitForSelector('.savedamount .pixel_separator, .description a') // 提取折扣数组,统一转成数字类型 const discounts = await page.$$eval('.savedamount .pixel_separator', (discountEls) => { return discountEls.map(el => { const numStr = el.innerText.replace(/[^0-9.]/g, '').replace(/\D+/g,'0') return Number(numStr) }) }); // 提取所有商品链接数组 const allLinks = await page.$$eval('.description a', (allAs) => allAs.map(a => a.href)); // 遍历索引筛选符合条件的链接 const filteredLinks = [] for(let i = 0; i < discounts.length; i++){ if(discounts[i] > minDiscount){ filteredLinks.push(allLinks[i]) } } console.log('符合条件的商品链接:', filteredLinks) console.log('所有商品折扣:', discounts) await browser.close() } // 执行函数 getLinks()
修改点说明
- 把
minDiscount改为数字类型,避免字符串比较的逻辑错误 - 新增
waitForSelector等待页面元素渲染完成,避免元素未加载导致两个数组长度不匹配 - 统一将提取到的折扣字符串转成数字类型再做比较
- 遍历两个数组的对应索引,筛选出折扣大于20%的商品链接
- 新增浏览器关闭逻辑,避免进程残留
内容的提问来源于stack exchange,提问作者Faster than a snail
相关产品推荐
相关产品推荐

