Puppeteer 多行 waitForFunction 方法
Puppeteer multiline waitForFunction method
我正在使用 Puppeteer page.waitForFunction()
方法:
await page.waitForFunction(`
(window.hero.x - 1 === ${x} || window.hero.x === ${x} || window.hero.x + 1 === ${x} || window.hero.x === ${x}) && (window.hero.y - 1 === ${y} || window.hero.y === ${y} || window.hero.y + 1 === ${y} || window.hero.y === ${y}) || window.hero.x === ${x} && window.hero.y === ${y}
`);
它正在运行,但看起来很糟糕。我想将其更改为多行。 In docs 有:
page.waitForFunction(pageFunction[, options[, ...args]])
pageFunction <function|string>
Function to be evaluated in browser context
To pass arguments from node.js to the predicate of page.waitForFunction
function:
const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);
我这样试过:
console.log(x,y); // 24 42
await page.waitForFunction((x, y) => {
console.log(x, y); // undefined, undefined
if(x && y) {
return true;
}
});
但是我试图传递的 x
和 y
是未定义的。我做错了什么?
您需要将 x
和 y
参数传递给 waitForFunction
。
console.log(x,y); // 24 42
await page.waitForFunction((x, y) => {
console.log(x, y); // undefined, undefined
if(x && y) {
return true;
}
}, {}, x, y);
您需要传入 x
和 y
- 目前它们是参数。您还可以稍微简化您的功能:
await page.waitForFunction((x, y) => (x && y ? true : undefined), {}, x, y);
我正在使用 Puppeteer page.waitForFunction()
方法:
await page.waitForFunction(`
(window.hero.x - 1 === ${x} || window.hero.x === ${x} || window.hero.x + 1 === ${x} || window.hero.x === ${x}) && (window.hero.y - 1 === ${y} || window.hero.y === ${y} || window.hero.y + 1 === ${y} || window.hero.y === ${y}) || window.hero.x === ${x} && window.hero.y === ${y}
`);
它正在运行,但看起来很糟糕。我想将其更改为多行。 In docs 有:
page.waitForFunction(pageFunction[, options[, ...args]])
pageFunction
<function|string>
Function to be evaluated in browser contextTo pass arguments from node.js to the predicate of
page.waitForFunction
function:const selector = '.foo'; await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);
我这样试过:
console.log(x,y); // 24 42
await page.waitForFunction((x, y) => {
console.log(x, y); // undefined, undefined
if(x && y) {
return true;
}
});
但是我试图传递的 x
和 y
是未定义的。我做错了什么?
您需要将 x
和 y
参数传递给 waitForFunction
。
console.log(x,y); // 24 42
await page.waitForFunction((x, y) => {
console.log(x, y); // undefined, undefined
if(x && y) {
return true;
}
}, {}, x, y);
您需要传入 x
和 y
- 目前它们是参数。您还可以稍微简化您的功能:
await page.waitForFunction((x, y) => (x && y ? true : undefined), {}, x, y);