Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I got document is not defined error in puppeteer?

I'd like to simulate a click on a gallery (<div class="image">) but when I try to run this code, I got document not defined error.

async function gallery(page) {
 await page.waitFor(3000);
 await page.click(document.querySelector('.div image'));
}

What's the problem here? How can I use document.querySelector correctly with puppeteer?

like image 753
Con Troll Avatar asked Apr 16 '19 07:04

Con Troll


People also ask

How do I fix document not defined error?

To solve the"ReferenceError: document is not defined" error, make sure to only use the document global variable on the browser. The variable relates to the Document Object Model, which represents a web page that is loaded in the browser and can't be used on the server side (e.g. in Node. js).

Why is document not defined?

The most common reason for this error is because you're using Node. That is to say, you are trying to access the document object on the server, but the server does not have access to the document object because it lives on the browser.

How do you get puppeteer to text?

We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.

Is not defined at JS?

A not defined error is when we did not declare the variable and tried to call that variable. In JavaScript, we can declare variables without adding const , let , or var , and we won't get an error of undefined or not defined . This can be seen in the code below.


1 Answers

I think document would only be available within page.evaluate (according to puppeteer documentation )

Try:

async function gallery(page) {
   await page.waitFor(3000);
   await page.evaluate(() => {
      document.querySelector('div.image').click();
   })
}
like image 164
Kushagra Sharma Avatar answered Oct 03 '22 03:10

Kushagra Sharma