我正在尝试将变量传递给Puppeteer中的page.evaluate()函数,但是当我使用以下非常简化的示例时,变量是未定义的.evalVar
我是Puppeteer的新手,找不到任何构建的例子,所以我需要帮助将该变量传递给page.evaluate()函数,以便我可以在里面使用它.
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const evalVar = 'WHUT??';
try {
await page.goto('https://www.google.com.au');
await page.waitForSelector('#fbar');
const links = await page.evaluate((evalVar) => {
console.log('evalVar:', evalVar); // appears undefined
const urls = [];
hrefs = document.querySelectorAll('#fbar #fsl a');
hrefs.forEach(function(el) {
urls.push(el.href);
});
return urls;
})
console.log('links:', links);
} catch (err) {
console.log('ERR:', err.message);
} finally {
// browser.close();
}
})();
Run Code Online (Sandbox Code Playgroud) 每当我尝试传递一个函数时,就像这样:
var myFunc = function() { console.log("lol"); };
await page.evaluate(func => {
func();
return true;
}, myFunc);
Run Code Online (Sandbox Code Playgroud)
我得到:
(node:13108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: TypeError: func is not a function
at func (<anonymous>:9:9)
(node:13108) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud)
为什么?如何正确做?
谢谢!
€:让我澄清一下:我这样做是因为我想先找到一些DOM元素,然后在该函数内部使用它们,更像这样(简化):
var myFunc = function(element) { element.innerHTML = "baz" };
await page.evaluate(func => { …Run Code Online (Sandbox Code Playgroud) 最近,我在一个新项目中使用了 Puppeteer。
我对 API 的一部分有一些我不明白的问题。文档对于这些API的介绍非常简单:
page.exposeFunctionpage.evaluateOnNewDocument可以给我一个详细的演示以便更好地理解吗?
我正在使用Puppeteer用于无头Chrome.我希望评估页面内部的一个函数,该函数使用在其他地方动态定义的其他函数的部分.
下面的代码是最小的示例/证明.实际上functionToInject()并且otherFunctionToInject()更复杂并且需要页面DOM.
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(someURL);
var functionToInject = function(){
return 1+1;
}
var otherFunctionToInject = function(input){
return 6
}
var data = await page.evaluate(function(functionToInject, otherFunctionToInject){
console.log('woo I run inside a browser')
return functionToInject() + otherFunctionToInject();
});
return data
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到:
错误:评估失败:TypeError:functionToInject不是函数
我理解的是:functionToInject没有被传递到页面的JS上下文中.但是如何将其传递到页面的JS上下文中?
javascript headless-browser google-chrome-headless puppeteer
根据这个响应,是否有一种方法(比如使用casperjs/phantomjs)在page.evaluate()上下文中添加我们的自定义函数?
例如,包含一个带辅助函数的文件x来调用Xpath函数:x('//a/@href')