[英]How to iterate selector over puppeter
Dear everybody I have a problem with selector in puppeter.亲爱的大家,我对 puppeter 中的选择器有疑问。
I have this code.我有这个代码。
for(var k= 0 ; k<= 21 ; k++) {
const text = await page.evaluate(() => {
document.querySelector(
'div.ui-table__row:nth-child('+k+') > a:nth-child(1) > div:nth-child(2)'
).textContent
})
console.log(text);
}
The problem when I try to execute this snippet is that I don't have defined k but i think that is correct.当我尝试执行此代码段时的问题是我没有定义 k 但我认为这是正确的。
Error: Evaluation failed: ReferenceError: k is not defined
How I can solve this problem?我该如何解决这个问题? Regards
问候
k
needs to be explicitly passed/injected into evaluate()
k
需要显式传递/注入到evaluate()
const k = 'foo'
await page.evaluate(k => {...}, k)
According to this document , You have to pass the variable as an argument to the page.evaluate
like this:根据此文档,您必须将变量作为参数传递给
page.evaluate
,如下所示:
const result = await page.evaluate((x) => { // 1. Define "x" to get value in the step 2
return Promise.resolve(8 * x); // 3. Return the result
}, 7); // 2. Pass 7 to "x"
console.log(result); // prints "56"
Your snippet will look like this:您的代码段将如下所示:
for(let k = 0; k <= 21; k++) {
const text = await page.evaluate((nth) => {
return document.querySelector(
'div.ui-table__row:nth-child('+ nth +') > a:nth-child(1) > div:nth-child(2)'
).textContent; // Return `textContent` to "out side"
}, k)
console.log(text);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.