[英]Puppeteer's page.evaluate does not consider i in for loop
I've been trying to iterate over a list of divs, nearly identical besides the data displayed in them, that are under a certain section of the dom, <aside>
, in order to grab the innerText from each one of them.我一直在尝试遍历一个 div 列表,除了其中显示的数据之外几乎相同,它们位于 dom 的某个部分
<aside>
下,以便从它们中的每个中获取 innerText 。 The result functions properly when hardcoding an nth-child
number, however, trying to iterate it in a for loop produces the error: Error: Evaluation failed: ReferenceError: i is not defined at __puppeteer_evaluation_script__:1:130
.当硬编码
nth-child
数字时,结果可以正常运行,但是,尝试在 for 循环中对其进行迭代会产生错误: Error: Evaluation failed: ReferenceError: i is not defined at __puppeteer_evaluation_script__:1:130
。 Confused as to what's going on here.对这里发生的事情感到困惑。
for (let i = 1; i < 9; i++) {
let info = await page.evaluate(
() => [...document.querySelectorAll(`#root > main > div.sc-jcVebW.eVwwrC > div.sc-bZSQDF.dgraCx > div > aside > div:nth-child(${i}) > div.sc-dlfnbm.ujoHC > div.sc-hKgILt.beOqPu > div > h2`)].map(elem => elem.innerText)
);
console.log(info)
}
Functions passed to page.evaluate
get stringified so they can be run in the browser, so they don't have lexical scope inheritance that one would normally expect.传递给
page.evaluate
的函数被字符串化,因此它们可以在浏览器中运行,因此它们没有人们通常期望的词法 scope inheritance。 You need to pass another argument to page.evaluate
to indicate the parameters the function should take.您需要将另一个参数传递给
page.evaluate
以指示 function 应采用的参数。
I'd also recommend making the code more readable: put the long selector on its own line, and use const
instead of let
(if at all possible):我还建议使代码更具可读性:将长选择器放在自己的行上,并使用
const
而不是let
(如果可能的话):
const info = await page.evaluate(
(i) => {
const selector = `#root > main > div.sc-jcVebW.eVwwrC > div.sc-bZSQDF.dgraCx > div > aside > div:nth-child(${i}) > div.sc-dlfnbm.ujoHC > div.sc-hKgILt.beOqPu > div > h2`;
return [...document.querySelectorAll(selector)]
.map(elem => elem.innerText);
},
i
);
Also consider if .innerText
is really what you need - it usually isn't .还要考虑
.innerText
是否真的是你需要的——它通常不是。 Use .textContent
instead if you can.如果可以,请改用
.textContent
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.