找不到指定 ID 未定义的上下文



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

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

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')

不可序列化,因此它返回 undefined(请参阅此问题作为参考(

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

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

这是一个很长的死线程,但如果有人遇到这个问题并且上述答案不适用于您,请尝试添加一个简单的await page.waitForTimeout(2000)。我的测试正在完成,但在尝试await browser.close();时收到此错误 在搜索最终选择器后添加等待似乎已经解决了这个问题。

最新更新