用playwright写一段允许js并获取执行结果的代码
下面是使用Playwright在浏览器中运行JavaScript并获取结果的示例代码:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
const result = await page.evaluate(() => {
// 在这里输入要执行的JS代码
return 2 + 2;
});
console.log(`执行结果为 ${result}`);
await browser.close();
})();
在这个示例中,我们使用Playwright来启动一个Chromium浏览器,并在新页面中执行一段JS代码。我们通过page.evaluate()方法执行这段代码,并使用return语句返回结果。我们将结果存储在result变量中,并在控制台中打印输出。
请注意,Playwright还支持在其他类型的浏览器中运行代码,如Firefox和WebKit。要使用其他浏览器,请将chromium更改为firefox或webkit。
原文地址: https://www.cveoy.top/t/topic/bZb5 著作权归作者所有。请勿转载和采集!