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?
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).
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.
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.
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.
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();
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With