Andrea D_
Andrea D_

Reputation: 2141

How to get the src attribute of an image with Puppeteer? I am getting 'Cannot read property 'getAttribute' of null' error

I am working with Puppeteer and trying to download an image. On Chrom dev tool console this returns what I want:

document.querySelector('.photo img').getAttribute('src')

but with Puppeteer evaluate function the same code :

let imageSrc = await page.evaluate(() => {
  return document.querySelector('.photo img').getAttribute('src');
});

throws an error:

error:  Error: Evaluation failed: TypeError: Cannot read property 'getAttribute' of null

Any idea why is this happening?

Upvotes: 1

Views: 2367

Answers (1)

Kodziak
Kodziak

Reputation: 151

Probably you have to wait for the element.

await page.waitForSelector('.photo img');
const imgSrc = await page.$eval('.photo img', (el) => el.getAttribute('src'));

or

await page.waitForSelector('.photo img');
const imgSrc = await page.$eval('.photo img', (el) => el.src); // Not sure if gonna work

Upvotes: 6

Related Questions