我们使用 Chrome 录音机并将录音导出为 puppeteer Javascript 文件,这些文件位于 CommonJS 中。它们与节点一起运行良好。
将 puppeteer 导入更改为 ESM,我们收到错误:
TypeError: Cannot read properties of undefined (reading 'race')
。
这是什么原因以及如何解决?
// const puppeteer = require('puppeteer'); // CommonJS
import puppeteer from 'puppeteer-core'; // ESM
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const timeout = 30000;
page.setDefaultTimeout(timeout);
{
const targetPage = page;
await targetPage.setViewport({
width: 1920,
height: 1200
})
}
{
const targetPage = page;
const promises = [];
const startWaitingForEvents = () => {
promises.push(targetPage.waitForNavigation());
}
startWaitingForEvents();
await targetPage.goto('http://localhost:4200/');
await Promise.all(promises);
}
{
const targetPage = page;
await puppeteer.Locator.race([ <--------------------
targetPage.locator('app-header li:nth-of-type(1) > a'),
targetPage.locator('::-p-xpath(/html/body/app-root/app-layout/app-header/nav/div/div/ul/li[1]/a)'),
targetPage.locator(':scope >>> app-header li:nth-of-type(1) > a'),
targetPage.locator('::-p-aria( Override User)'),
targetPage.locator('::-p-text(Override User)')
])
.setTimeout(timeout)
.click({
offset: {
x: 68.199951171875,
y: 11.625,
},
});
}
我们希望使用mocha,并尽可能少地调整导出的录音。 我们可以使用 Promise.race 代替 puppeteer.Locator.race。但以下内容对我们来说不是一个选择,因为我们需要调整整个文件:
const elementPromises = [
page.waitForSelector('app-header li:nth-of-type(1) > a'),
page.waitForSelector('::-p-xpath(/html/body/app-root/app-layout/app-header/nav/div/div/ul/li[1]/a)'),
page.waitForSelector(':scope >>> app-header li:nth-of-type(1) > a'),
page.waitForSelector('::-p-aria( Override User)'),
page.waitForSelector('::-p-text(Override User)')
];
const firstElement = await Promise.race(elementPromises);
await firstElement.click({
offset: { x: 68.199951171875, y: 11.625 }
});
两种选择:
import puppeteer, {Locator} from "puppeteer"; // ^23.3.0
console.log(!!Locator.race); // => true
或者使用 CSS 逗号“OR”运算符:
await targetPage
.locator(
`app-header li:nth-of-type(1) > a,
::-p-xpath(/html/body/app-root/app-layout/app-header/nav/div/div/ul/li[1]/a),
:scope >>> app-header li:nth-of-type(1) > a,
::-p-aria( Override User),
::-p-text(Override User)`
)
.setTimeout(timeout)
.click({
offset: {
x: 68.199951171875,
y: 11.625,
},
});