英文:
Puppeteer : how to pass argument to page evaluate?
问题
我想要传递一个参数给Puppeteer的page.evaluate
方法。
我可能仍然在 struggle with async/await that I don't master,所以我的知识问题可能更一般。无论如何,Puppeteer是当前需要解决的问题。
我有这段代码来更新一个<span>
元素。它工作得很好:
await page.evaluate(
() =>
(document.querySelector(
"selector"
).innerHTML = "WHATEVER")
);
"WHATEVER"的值来自外部变量。我需要将它传递给evaluate。
我尝试过:
const value = "WHATEVER"
async function setValue(val) {
console.log(val) //OK
await page.evaluate(
()=>{
console.log(val) // KO Error [ReferenceError]: val is not defined
document.querySelector(
"selector"
).innerHTML = val
}
);
}
await setValue(value) // KO
为什么val没有被定义?
在这种情况下如何传递参数给page evaluate?是否有替代方法?
英文:
I want to pass an argument to Puppeteer page evaluate
method.
I might just be still struggling with async/await that I don't master,so my knowledge issue might be more general. Anyway Puppeteer is the current problem to be solved.
I have this snippet for updating a <span> element. It works well:
await page.evaluate(
() =>
(document.querySelector(
"selector"
).innerHTML = "WHATEVER")
);
"WHATEVER" value comes from an outside variable. I need to pass it along to evaluate.
I tried with :
const value = "WHATEVER"
async function setValue(val) {
console.log(val) //OK
await page.evaluate(
() =>{
console.log(val) // KO Error [ReferenceError]: val is not defined
document.querySelector(
"selector"
).innerHTML = val
}
);
}
await setValue(value) // KO
Why is val not defined?
How to pass an argument to page evaluate in this case? Is there an alternative?
答案1
得分: 1
`page.evaluate()`与Node.js环境隔离,这意味着它无法访问来自Node.js脚本范围的变量。
要将参数传递给您提供给`page.evaluate()`的函数,您应将其作为额外的参数包括在内。
实际上,这是方法签名:
page.evaluate(pageFunction, ...args);
所以你需要像这样做:
const value = "WHATEVER"
async function setValue(val) {
console.log(val) //OK
await page.evaluate(
(val) => {
console.log(val) // 现在应该是OK的
document.querySelector("selector").innerHTML = val
},
val // 这是您将参数'val'传递给page.evaluate()中的函数的地方
);
}
await setValue(value)
英文:
page.evaluate()
is isolated from the Node.js environment, which means it does not have access to variables from your Node.js script scope.
To pass an argument to the function you provide to page.evaluate()
, you should include it as an additional parameter.
In fact this is the method signature:
page.evaluate(pageFunction, ...args);
So u need to so something like this:
const value = "WHATEVER"
async function setValue(val) {
console.log(val) //OK
await page.evaluate(
(val) => {
console.log(val) // Should be OK now
document.querySelector("selector").innerHTML = val
},
val // This is where you're passing the argument 'val' to the function in page.evaluate()
);
}
await setValue(value)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论