我试图从超市网站上获取所有类别的所有产品名称和价格,我发现的所有教程仅针对一个const url进行操作,我需要遍历所有这些。到目前为止,我已经知道了
const puppeteer = require('puppeteer');
async function scrapeProduct(url) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const [el2] = await page.$x('//*[@id="product-nonfood-page"]/main/div/div/div[1]/div[1]/div/div[2]/h1/div');
const text2 = await el2.getProperty('textContent');
const name = await text2.jsonValue();
const [el] = await page.$x('//*[@id="product-nonfood-page"]/main/div/div/div[1]/div[1]/div/div[2]/div[2]/div[1]/div[2]/p[1]/em[2]/strong/text()');
const text = await el.getProperty('textContent');
const price = await text.jsonValue();
console.log({name,price});
await browser.close();
}
scrapeProduct('https://www.jumbo.com.ar/gaseosa-sprite-sin-azucar-lima-limon-1-25-lt/p');
仅适用于一个。我正在使用nodejs和puppeteer。我怎样才能做到这一点?
您可以尝试for...of
使用单个浏览器实例和单个页面进行循环,以使抓取工具不会使服务器超载:
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
const urls = [
'https://www.jumbo.com.ar/gaseosa-sprite-sin-azucar-lima-limon-1-25-lt/p',
// ...
];
for (const url of urls) {
await page.goto(url);
const [el2] = await page.$x('//*[@id="product-nonfood-page"]/main/div/div/div[1]/div[1]/div/div[2]/h1/div');
const text2 = await el2.getProperty('textContent');
const name = await text2.jsonValue();
const [el] = await page.$x('//*[@id="product-nonfood-page"]/main/div/div/div[1]/div[1]/div/div[2]/div[2]/div[1]/div[2]/p[1]/em[2]/strong/text()');
const text = await el.getProperty('textContent');
const price = await text.jsonValue();
console.log({name,price});
}
await browser.close();
} catch (err) {
console.error(err);
}
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句