javascript - 找不到指定 id 未定义的上下文

标签 javascript node.js puppeteer

我正在尝试创建一个应用程序,对随机单词进行谷歌图像搜索并选择/单击第一个结果图像。

我成功了,直到代码尝试选择结果图像并在我的终端中抛出以下错误:

 UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection 
 id: 1): Error: Protocol error (Runtime.callFunctionOn): Cannot find 
 context with specified id undefined

这是我的代码:

const pup = require('puppeteer');
const random = require('random-words');
const url = 'http://images.google.com';

(async() => {
  const browser = await pup.launch({headless: false});
  const page = await browser.newPage();

  await page.goto(url);
  const searchBar = await page.$('#lst-ib');
  await searchBar.click();
  await page.keyboard.type(`${random()}`);
  const submit = await page.$('#mKlEF');
  await submit.click();
  await page.keyboard.type(random());
  await page.keyboard.press('Enter');
  const pic = await page.evaluate(() => {
    return document.querySelectorAll('img');
  });

  pic.click();
})();

最佳答案

document.querySelectorAll('img') 不可序列化,因此它返回未定义(请参阅此 issue 作为引用)

请使用类似以下内容:(取决于您要单击的元素)

await page.$$eval('img', elements => elements[0].click());

关于javascript - 找不到指定 id 未定义的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480342/

相关文章:

javascript - 如何在动态输入上使用 GetElementsByClassName()

firebase - Cloud Functions 中的 puppeteer.launch 抛出错误

node.js - forEach 中的 Puppeteer 测试

jestjs - 无法使用 jest + puppeteer 获得测试覆盖率

javascript - 如何将脚本加载到 webpack 中

node.js - 从Web服务器发送请求到本地服务器

javascript - 在 Firefox 中单击内部 2-3 次时,光标移动到带有占位符 css 的 contenteditable div 之外

php - 在多个页面之间循环(刷新)?

javascript - 用于显示 html 内容的 WebView 与 TextView

javascript - 如何扁平化 V8 ConsString?