Dan*_*jor 28 javascript node.js playwright
我正在尝试一些非常简单的事情:
如此简单,但我无法让它发挥作用。这是代码:
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();
}
}
})();
Run Code Online (Sandbox Code Playgroud)
起初我试图用 a 得到第一个结果,page.$()但没有成功。在对这个问题进行了一些调查之后,我发现page.waitForNavigation()我认为这是解决方案,但事实并非如此。
我正在使用最新的剧作家版本:1.0.2。
the*_*ton 10
在我看来,唯一的问题是您最初的承诺组合,我刚刚将承诺重构为 async/await 并使用它page.$eval来检索它textContent,它工作得很好,不再有目标关闭错误。
try {\n const context = await browser.newContext();\n const page = await context.newPage();\n await page.goto(\'https://google.com\');\n await page.fill(\'input[name=q]\', \'cheese\');\n await page.press(\'input[name=q]\', \'Enter\');\n await page.waitForNavigation();\n\n // page.waitForSelector(\'div#rso h3\').then(firstResult => console.log(`${browserType}: ${firstResult.textContent()}`)).catch(error => console.error(`Waiting for result: ${error}`));\n\n await page.waitForSelector(\'div#rso h3\');\n const firstResult = await page.$eval(\'div#rso h3\', firstRes => firstRes.textContent);\n console.log(`${browserType}: ${firstResult}`)\n } catch(error) {\n console.error(`Trying to run test on ${browserType}: ${error}`);\n } finally {\n await browser.close();\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n输出:
\nchrome: Cheese \xe2\x80\x93 Wikipedia\nfirefox: Cheese \xe2\x80\x93 Wikipedia\nwebkit: Cheese \xe2\x80\x93 Wikipedia\nRun Code Online (Sandbox Code Playgroud)\n注意: chrome 和 webkit 可以工作,firefox 对我来说失败waitForNavigation。如果我把它换成await page.waitForTimeout(5000);firefox也可以。这可能是剧作家的 Firefox 对导航承诺的支持存在问题。
如果你等待,那么上班page.press('input[name=q]', 'Enter');可能就太晚了。waitForNavigation
您可以删除await新闻发布会上的内容。您可能需要等待导航,而不是按下操作。
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()}`);
Run Code Online (Sandbox Code Playgroud)
另请注意,您需要awaitfor textContent().
| 归档时间: |
|
| 查看次数: |
73670 次 |
| 最近记录: |