admin管理员组

文章数量:1208155

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?

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?

Share Improve this question edited Apr 16, 2019 at 7:25 Con Troll asked Apr 16, 2019 at 7:18 Con TrollCon Troll 1591 gold badge1 silver badge9 bronze badges 6
  • 2 There is no document in node. – Keith Commented Apr 16, 2019 at 7:20
  • But with puppeteer's browser there is, rigth? So I should be able to use document.querySelector – Con Troll Commented Apr 16, 2019 at 7:23
  • I have collected other elements with the code const partnersOnPage = await page.evaluate(() => Array.from(document.querySelectorAll('div.listing__card a.listing__thumbnail')) .map(element => element.href.substring(element.href.lastIndexOf('/') + 1)) ); so there is document in nodejs and puppeteer. – Con Troll Commented Apr 16, 2019 at 7:28
  • 3 I think document would only be available within page.avaluate (according to github.com/GoogleChrome/puppeteer) Try: async function gallery(page) { await page.waitFor(3000); await page.evaluate(() => { document.querySelector('div.image').click(); }) } – Kushagra Sharma Commented Apr 16, 2019 at 7:32
  • 3 But with puppeteer's browser there is, rigth? No, there is still no document, Chromium has a document, and that's what puppeteer is controlling. Basically you just need to call click inside the chromium instance,.. page.evaluate is one way, but an easier option is page.$('div.image').click(). I was on mobile with my original response, so couldn't give a full response, but hoped it might have given you a hint to what was wrong.. :) – Keith Commented Apr 16, 2019 at 9:29
 |  Show 1 more comment

2 Answers 2

Reset to default 12

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();
   })
}

you are calling invalid element , you can check this document

await page.evaluate(() => {
  document.querySelector('div.image').click();
});

本文标签: javascriptWhy I got document is not defined error in puppeteerStack Overflow