Home > Back-end >  Puppeteer to save image open in the browser
Puppeteer to save image open in the browser

Time:02-14

I have a link for a (gif) image, obtained manually via 'open in new tab'. I want Puppeteer to open the image and then save it to a file. If doing it in a normal browser I would click right button and choose 'save' from the context menu. Is there a simple way to perform this action in Puppeteer?

CodePudding user response:

In Puppeteer it's possible to right click, but it's not possible to automate the navigation through the "save as" menu. However, there is a solution outlined in the top answer here:

How can I download images on a page using puppeteer?

You can write the images to disk directly from the page response.

CodePudding user response:

These lines of codes below will save Wikipedia image logo as filename logo.png

import * as fs from 'fs'
import puppeteer from 'puppeteer'
;(async () => {
    const wikipedia = 'https://www.wikipedia.org/'
    const browser = await puppeteer.launch()
    const page = (await browser.pages())[0]
    const get = await page.goto(wikipedia)
    const image = await page.waitForSelector('img[src][alt="Wikipedia"]')
    const imgURL = await image.evaluate(img => img.getAttribute('src'))
    const pageNew = await browser.newPage()
    const response = await pageNew.goto(wikipedia   imgURL, {timeout: 0, waitUntil: 'networkidle0'})
    const imageBuffer = await response.buffer()
    await fs.promises.writeFile('./logo.png', imageBuffer)
    await page.close()
    await pageNew.close()
    await browser.close()
})()

Please select this as the right answer if this help you.

  • Related