0

I'm using Puppeteer to download images from a website. For now it works well for a single image but I need it to deal with all images inside that div.item-wrapper. How it can be done?

let imagefile = await page.evaluate(async () => {
    let imagefile
    try {
        imagefile = document.querySelector('div.item-wrapper img').src
    } catch(e) {
        imagefile = null
    }

    return imagefile
})
var imagefileDL = await page.goto(imagefile);
fs.writeFile('./uploads/' + imagefile.replace(/^.*[\\\/]/, ''), await imagefileDL.buffer(), function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
});
  • Research: 1) how to get several elements from DOM 2) get those URLs 3) then with those URLs, do something like this: https://stackoverflow.com/a/51624229/2715393 – Vaviloff Aug 20 '20 at 13:36
  • you may find this helpful, to allow multiple downloads,https://stackoverflow.com/a/73164259/14085862 this doesn't cover HOW part as it belongs to your own logic. – Muhammad Uzair Jul 29 '22 at 09:18

1 Answers1

1

You can try something like this:

let imagefiles = await page.evaluate(() =>
    Array.from(
      document.querySelectorAll('div.item-wrapper img'),
      img => img.src
    )
);

for (const imagefile of imagefiles) {
  const imagefileDL = await page.goto(imagefile);
  fs.writeFile('./uploads/' + imagefile.replace(/^.*[\\\/]/, ''), await imagefileDL.buffer(), function(err) {
      if(err) {
          return console.log(err);
      }

      console.log("The file was saved!");
  });
}
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26