为了账号安全,请及时绑定邮箱和手机立即绑定

嵌套等待无法正常工作 Puppeteer

嵌套等待无法正常工作 Puppeteer

长风秋雁 2023-07-14 16:25:26
在此代码中,我尝试过滤掉 ElementHandle 数组的部分内容。我检查它是否有效的方法是打印最终过滤数组的长度。应该是 4,而不是 30。const ar = await page.$$("li[class*=react-job-listing]");const shortArray = Array.from(ar).filter(async (el)=> {    console.log((await (await el.getProperty("innerText")).jsonValue()).includes("Easy Apply"));    return (await (await el.getProperty("innerText")).jsonValue()).includes("Easy Apply");});//console.log((await (await ar[0].getProperty("innerText")).jsonValue()).includes("Easy Apply"));console.log(shortArray.length);console.log('hello');不幸的是,这就是结果。30hellofalsefalsefalsefalsetruefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsetruefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsetruefalse长度的控制台日志出现在过滤器执行之前,而它应该是最后一件事。看来脚本并没有等待等待。一定是由于多重嵌套的等待造成的。但我不知道如何解决它。我知道这真的很难看。但由于某些原因我现在无法使用 page.evaluate 和 DOM 函数。请暂时看一下。
查看完整描述

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


查看完整回答
反对 回复 2023-07-14
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信