1 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
這不是傀儡師的錯(cuò)。異步函數(shù)返回 Promise,因此在Array.from(ar).filter()每個(gè) callbak 中都返回 thruthy 值,并且不會(huì)過(guò)濾掉任何內(nèi)容。使用for..of循環(huán)進(jìn)行異步操作更簡(jiǎn)單、更安全:
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
添加回答
舉報(bào)