每当我尝试传递一个函数时,就像这样:
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脚本,用于exposeFunction()在无头Chrome中运行一些东西.
(async function(){
var log = console.log.bind(console),
puppeteer = require('puppeteer');
const browser = await puppeteer.launch();
const page = await browser.newPage();
var functionToInject = function(){
return window.navigator.appName;
}
await page.exposeFunction('functionToInject', functionToInject);
var data = await page.evaluate(async function(){
console.log('woo I run inside a browser')
return await functionToInject();
});
console.log(data);
await browser.close();
})()
Run Code Online (Sandbox Code Playgroud)
这失败了:
ReferenceError: window is not defined
Run Code Online (Sandbox Code Playgroud)
其中指的是注入的功能.如何window在无头Chrome内部进行访问?
我知道我可以做evaluate(),但这不适用于我动态传递的函数:
(async function(){
var log = console.log.bind(console),
puppeteer = require('puppeteer');
const browser = await puppeteer.launch(); …Run Code Online (Sandbox Code Playgroud) 我正在使用 Puppeteer 解析网页,但找不到我的问题的明确答案。
我试图将一个函数作为参数传递给page.evaluate() 一个对象可以传递但似乎无法传递一个函数。这是一个人为的例子:
const obj = {
thing: 'thing1',
};
const myfunction = () => {
return `great ${stuff}`;
};
await page.evaluate((obj, function)=>{
const thing = myfunction;
},(obj, function));
Run Code Online (Sandbox Code Playgroud)
是否可以将函数作为参数传递给 puppeteers page.evaluate()?
我一直看到这个错误代码
page.on('console', msg => console.log(msg.text()));
Run Code Online (Sandbox Code Playgroud)
这失败
console.log('Hello %s', 'World');
Run Code Online (Sandbox Code Playgroud)
产生
Hello World // browser
Hello %s World // puppeteer
Run Code Online (Sandbox Code Playgroud)
好,所以我想也许我可以做到
page.on('console', msg => console.log(...msg.args()));
Run Code Online (Sandbox Code Playgroud)
NOPE:那倒掉了一些巨大的JSHandle东西。
好吧,也许
page.on('console', msg => console.log(...msg.args().map(a => a.toString());
Run Code Online (Sandbox Code Playgroud)
NOPE:打印
JSHandle: Hello %s JSHandle: World
Run Code Online (Sandbox Code Playgroud)
我想我可以通过删除前9个字符来破解它。
我也试过
page.on('console', msg => console.log(...msg.args().map(a => a.jsonValue())));
Run Code Online (Sandbox Code Playgroud)
NOPE:打印
Promise { <pending> } Promise { <pending> }
Run Code Online (Sandbox Code Playgroud)
好吧
page.on('console', async(msg) => {
const args = Promise.all(msg.args().map(a => a.jsonValue()));
console.log(...args);
});
Run Code Online (Sandbox Code Playgroud)
不,那是打印
UnhandledPromiseRejectionWarning: TypeError: Found non-callable @@iterator
UnhandledPromiseRejectionWarning: Unhandled …Run Code Online (Sandbox Code Playgroud) 我正在尝试以编程方式从 JavaScript 中的https://rarity.tools/upcoming/页面访问表中的数据。由于该网站通过 JavaScript 加载,因此我一直在使用 puppeteer。该网站有多个表(总共 4 个),我希望能够引用每个表并检查它们有多少行。
我最初尝试使用 nth-of-type,但我尝试从中接收数据的网站似乎没有以允许我使用 nth-of-type 或 nth-child 的方式构建其页面(请请参阅:在 javascript 错误中使用 pupeteer 访问第 n 个表并计算行数:“无法找到与选择器“table:nth-of-type(2) > tr”匹配的元素”” )。
相反,我尝试创建一个 for 循环来将每个表的innerHTML 设置为其自己的变量,然后根据索引分析HTML 字符串。如果我对数字进行硬编码,以下内容将返回正确的值:
console.log(table_html)
let table_html = await page.evaluate(
() => document.querySelectorAll('table')[2].innerHTML
)
Run Code Online (Sandbox Code Playgroud)
但是,一旦我将其设置为循环:
for (let j = 0; j < numTables; j++) {
let table_html = await page.evaluate(
(j) => document.querySelectorAll('table')[j].innerHTML
)
console.log(table_html)
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
错误:评估失败:TypeError:无法在ExecutionContext._evaluateInternal 处的puppeteer_evaluation_script :1:46 处读取未定义的属性(读取“innerHTML”)(C:\Users\kylel\Desktop\NFTSorter_IsolatedJS\node_modules\puppeteer\lib\cjs
puppeteer\common \ExecutionContext.js:221:19) 在 processTicksAndRejections (internal/process/task_queues.js:95:5) 在异步 ExecutionContext.evaluate (C:\Users\kylel\Desktop\NFTSorter_IsolatedJS\node_modules\puppeteer\lib\cjs\pup peteer\common\ExecutionContext.js:110:16) 在异步获取 (C:\Users\kylel\Desktop\NFTSorter_IsolatedJS\app.js:35:30)
所有代码: …
我正在使用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
这是我第一次使用 puppeteer 进行测试。但我在运行时遇到了一个奇怪的错误
\n我想做的是在页面中运行这个函数,但是
\nconst puppeteer = require('puppeteer'); \nlet browser, page,\n//evaluates to file://C:/Users/chris/Google Drive/code projects/text translation sheet/test/src/index.html\n htmlFilepath = "file://" + path.resolve(__dirname, "src/index.html");\nbrowser = await puppeteer.launch();\npage = await browser.newPage();\nawait page.goto(htmlFilepath); \npage.exposeFunction(getMaxWordsInContentArea.name, getMaxWordsInContentArea)\n \nconst lastWordThatFit = await page.evaluate(function(){\n \n const el = document.querySelector('.line__target-language-text')\n const elContainer = el.parent;\n const lastFitWordIndex = getMaxWordsInContentArea(el,elContainer,["Call", "me", "Ishmael.", "Some", "years", "ago\xe2\x80\x94never", "mind", "how", "long", "precisely\xe2\x80\x94having", "little", "or", "no", "money", "in", "my", "purse,", "and", "nothing", "particular", "to", "interest", "me", "on", "shore,", "I", "thought", "I", "would", …Run Code Online (Sandbox Code Playgroud) 假设脚本已导航到特定页面。如何在该脚本中执行js函数?
describe("TestSuite", () => {
test("Login", async() => {
await page.goto(APP);
await page.waitForSelector("[name=loginForm]");
await page.click("input[name=username]");
await page.type("input[name=username]", user.username);
await page.click("input[name=pwd]");
await page.type("input[name=pwd]", user.pwd);
await page.click("input[name=login]");
await page.waitForSelector(".PageBodyVertical");
// execute a js function x() here which is loaded with the page.
}, 60000);
Run Code Online (Sandbox Code Playgroud) 我正在循环浏览下拉列表,并尝试选择单个选项。如果我尝试使用模板文字,querySelector 将返回 null。
这里有两种不同的查询,一种带有模板文字,一种不带有模板文字。我正在使用反引号,一切都相同,但第一个查询返回 null,而第二个查询返回正确的值,即使在这种情况下“i”= 2。
const value = await self.page.evaluate(() => {
return document.querySelector(`select option:nth-child(${i})`);
});
const value1 = await self.page.evaluate(() => {
return document.querySelector(`select option:nth-child(2)`);
});
// Structure
for (let i = 2; i < options.length; i++){
if (options[i]....){
const value = await self.page.evaluate((i) => {
return document.querySelector(`select option:nth-child(${i})`);
});
}
}
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?