1 回答

TA贡献1830条经验 获得超3个赞
这不是傀儡师的错。异步函数返回 Promise,因此在Array.from(ar).filter()每个 callbak 中都返回 thruthy 值,并且不会过滤掉任何内容。使用for..of循环进行异步操作更简单、更安全:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const html = `
<!doctype html>
<html>
<head><meta charset='UTF-8'><title>Test</title></head>
<body>
<p>foo 1</p>
<p>foo 2</p>
<p>bar 1</p>
<p>bar 2</p>
</body>
</html>`;
try {
const [page] = await browser.pages();
await page.goto(`data:text/html,${html}`);
const ar = await page.$$("p");
const shortArray = [];
for (const element of ar) {
const text = await (await element.getProperty("innerText")).jsonValue();
console.log(text, text.includes("foo"));
if (text.includes("foo")) shortArray.push(element);
}
console.log(shortArray.length);
console.log('hello');
} catch(err) { console.error(err); } finally { await browser.close(); }
foo 1 true
foo 2 true
bar 1 false
bar 2 false
2
hello
添加回答
举报