【问题标题】:Why I got document is not defined error in puppeteer?为什么我在 puppeteer 中得到 document is not defined 错误?
【发布时间】:2019-09-06 05:30:00
【问题描述】:

我想模拟对图库 (<div class="image">) 的点击,但是当我尝试运行此代码时,我收到了文档未定义错误。

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

这里有什么问题?如何在 puppeteer 中正确使用 document.querySelector?

【问题讨论】:

  • 节点中没有文档。
  • 但是有了 puppeteer 的浏览器,对吧?所以我应该可以使用 document.querySelector
  • 我已经用代码const partnersOnPage = await page.evaluate(() => Array.from(document.querySelectorAll('div.listing__card a.listing__thumbnail')) .map(element => element.href.substring(element.href.lastIndexOf('/') + 1)) );收集了其他元素,所以nodejs和puppeteer中有文档。
  • 我认为document 只能在page.avaluate 内使用(根据github.com/GoogleChrome/puppeteer)尝试:async function gallery(page) { await page.waitFor(3000); await page.evaluate(() => { document.querySelector('div.image').click(); }) }
  • But with puppeteer's browser there is, rigth? 不,仍然没有文档,Chromium 有文档,这就是 puppeteer 控制的。基本上你只需要在 chromium 实例中调用 click,..page.evaluate 是一种方法,但更简单的选择是page.$('div.image').click()。我在手机上使用了我的原始回复,所以无法给出完整的回复,但希望它能给你一个提示,告诉你出了什么问题.. :)

标签: javascript node.js async-await puppeteer


【解决方案1】:

我认为文档只能在 page.evaluate 内使用(根据 puppeteer documentation

试试:

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

【讨论】:

  • 在控制台调试时如何使用它?它似乎工作正常,但是当在调试模式下 page.eval 中出现突破时,它会给出 doc is not defined 错误
【解决方案2】:

你调用的元素无效,你可以查看document

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

【讨论】:

  • 我仍然得到文档也没有用div.image 定义。
  • 你可以看看这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2012-06-13
  • 2020-04-08
相关资源
最近更新 更多