简体   繁体   English

尝试在 page.evaluate() 函数中执行 for 循环 - Puppeteer

[英]Trying to execute a for loop within the page.evaluate() function - Puppeteer

I am currently using Puppeteer to scrape a web page.我目前正在使用 Puppeteer 来抓取网页。 The web page specifically has div elements of nth-child that I am trying to iterate through.该网页特别具有我试图迭代的nth-child div 元素。 Without a for-loop I can successfully retrieve the innerText of a div.ticker element but if I add a for-loop to retrieve the innerText of multiple div.ticker elements, then the code within for-loop fails to execute and instead jumps straight to line 11. No errors are surfacing upon execution which is making me struggle to find why my for-loop is not executing.如果没有 for 循环,我可以成功检索div.ticker元素的innerText但如果我添加一个 for 循环来检索多个div.ticker元素的innerText ,那么 for 循环中的代码将无法执行,而是直接跳转到第 11 行。执行时没有出现错误,这让我很难找到为什么我的 for 循环没有执行。

 let scrapeData = await page.evaluate(() => {
    for (let i = 1; i < 21; i++) {
      let element = document.querySelector("#optionflow > div.component-body.ps.ps--theme_default.ps--active-y > div.data-body > div:nth-child(" + i + ") > div.ticker").innerText;
      console.log(element);
    }

    return {
      element
    }
  });
  console.log("Hello world!");
  await browser.close();

  return scrapeData;
}

The element in return statement is not defined. return 语句中的element未定义。 You are declaring the element in the for loop scope and it's destroyed after the loop ends.您正在 for 循环范围内声明该element ,并在循环结束后将其销毁。

If there are multiple elements use array and push elements.如果有多个元素,请使用数组和推送元素。 But What you should really do is us querySelectorAll without the loop.但是你真正应该做的是我们querySelectorAll没有循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM