我正在尝试一些非常简单的事情:
- 导航到 google.com
- 用“奶酪”填充搜索框
- 在搜索框按回车
- 打印第一个结果的标题文本
如此简单,但我无法让它工作。这是代码:
const playwright = require('playwright');
(async () => {
for (const browserType of ['chromium', 'firefox', 'webkit']) {
const browser = await playwright[browserType].launch();
try {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://google.com');
await page.fill('input[name=q]', 'cheese');
await page.press('input[name=q]', 'Enter');
await page.waitForNavigation();
page.waitForSelector('div#rso h3')
.then(firstResult => console.log(`${browserType}: ${firstResult.textContent()}`))
.catch(error => console.error(`Waiting for result: ${error}`));
} catch(error) {
console.error(`Trying to run test on ${browserType}: ${error}`);
} finally {
await browser.close();
}
}
})();
起初我试图用 a 得到第一个结果,page.$()
但它没有用。在稍微调查了这个问题之后,我发现page.waitForNavigation()
我认为这是解决方案,但事实并非如此。
我正在使用最新的编剧版本:1.0.2。