Javascript 导航后剧作家错误(目标关闭)

Javascript 导航后剧作家错误(目标关闭),javascript,node.js,playwright,Javascript,Node.js,Playwright,我正在尝试一些非常简单的方法: 导航到google.com 用“奶酪”填充搜索框 在搜索框中按enter键 打印第一个结果标题的文本 这么简单,但我不能让它工作。代码如下: const playright=require('playright'); (异步()=>{ 用于(常量浏览器类型['chromium'、'firefox'、'webkit']){ const browser=等待剧作家[browserType].launch(); 试一试{ const context=await br

我正在尝试一些非常简单的方法:

  • 导航到google.com
  • 用“奶酪”填充搜索框
  • 在搜索框中按enter键
  • 打印第一个结果标题的文本
这么简单,但我不能让它工作。代码如下:

const playright=require('playright');
(异步()=>{
用于(常量浏览器类型['chromium'、'firefox'、'webkit']){
const browser=等待剧作家[browserType].launch();
试一试{
const context=await browser.newContext();
const page=wait context.newPage();
等待页面。转到('https://google.com');
等待page.fill('input[name=q],'cheese');
等待页面。按('input[name=q],'Enter');
等待page.waitForNavigation();
第页waitForSelector('div#rso h3')
.then(firstResult=>console.log(`${browserType}:${firstResult.textContent()}`)
.catch(error=>console.error(`Waiting for result:${error}`));
}捕获(错误){
错误(`尝试在${browserType}上运行测试:${error}`);
}最后{
等待浏览器关闭();
}
}
})();
起初,我试图通过
页面获得第一个结果。$()
,但没有成功。在对这个问题进行了一点调查之后,我发现
page.waitForNavigation()
是我认为可以解决的问题,但事实并非如此


我正在使用最新的剧作家版本:1.0.2。

如果您等待
页面,请按('input[name=q],'Enter')
waitForNavigation
waitForNavigation
可能已经太晚了

您可以在通话中删除
等待
。您可能需要等待导航,而不是按键操作

const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://google.com');
await page.fill('input[name=q]', 'cheese');
page.press('input[name=q]', 'Enter');
await page.waitForNavigation();

var firstResult = await page.waitForSelector('div#rso h3');
console.log(`${browserType}: ${await firstResult.textContent()}`);

另外请注意,对于
textContent()

您需要
wait
,在我看来,唯一的问题是您最初的承诺组合,我刚刚重构了异步/wait的承诺,并使用它检索
textContent
,它工作得很好,不再存在目标关闭错误

试试看{
const context=await browser.newContext();
const page=wait context.newPage();
等待页面。转到('https://google.com');
等待page.fill('input[name=q],'cheese');
等待页面。按('input[name=q],'Enter');
等待page.waitForNavigation();
//page.waitForSelector('div#rso h3')。然后(firstResult=>console.log(`${browserType}:${firstResult.textContent()}')).catch(error=>console.error(`Waiting for result:${error}');
等待页面。等待选民('div#rso h3');
const firstResult=wait page.$eval('div#rso h3',firstRes=>firstRes.textContent);
log(`${browserType}:${firstResult}`)
}捕获(错误){
错误(`尝试在${browserType}上运行测试:${error}`);
}最后{
等待浏览器关闭();
}
}
输出:

chrome: Cheese – Wikipedia
firefox: Cheese – Wikipedia
webkit: Cheese – Wikipedia

注意:chrome和webkit可以工作,firefox在
waitForNavigation
上失败。如果我将其替换为
wait page.waitForTimeout(5000)firefox也起了作用。这可能是因为playwright的Firefox支持导航承诺的问题。

等待或不等待页面。pres()我认为这无关紧要。我试过你的建议,不等待,但我仍然得到同样的错误。这不是问题所在。问题是它在导航之后不知何故失去了上下文。我也有同样的问题。它在导航之前使用页面的上下文。你有没有找到解决办法?