相关疑难解决方法(0)

如何在Puppeteers .evaluate()方法中传递函数?

每当我尝试传递一个函数时,就像这样:

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)

javascript google-chrome node.js puppeteer

8
推荐指数
2
解决办法
4167
查看次数

为什么我不能在使用Puppeteer的exposeFunction()函数中访问'window'?

我有一个非常简单的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)

google-chrome node.js headless-browser puppeteer

7
推荐指数
2
解决办法
5036
查看次数

是否可以将函数传递给 Puppeteer 的 page.evaluate()

我正在使用 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()?

javascript puppeteer

5
推荐指数
1
解决办法
1882
查看次数

如何在puppeter中打印页面的控制台输出,就像在浏览器中一样?

我一直看到这个错误代码

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 puppeteer

5
推荐指数
1
解决办法
69
查看次数

Puppeteer document.querySelectorAll 仅在循环中返回未定义“TypeError:无法读取未定义的属性(读取'innerHTML')”

我正在尝试以编程方式从 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)

所有代码: …

javascript loops querying web-scraping puppeteer

5
推荐指数
1
解决办法
853
查看次数

如何使用Puppeteer动态注入函数进行评估?

我正在使用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

4
推荐指数
1
解决办法
5102
查看次数

错误:评估失败:无效参数:应该恰好是一个字符串。| Puppeteer .evaluate() 错误

这是我第一次使用 puppeteer 进行测试。但我在运行时遇到了一个奇怪的错误

\n

我想做的是在页面中运行这个函数,但是

\n
const 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)

javascript puppeteer

4
推荐指数
1
解决办法
755
查看次数

在puppeteer中自动化时如何在页面上执行js函数?

假设脚本已导航到特定页面。如何在该脚本中执行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)

javascript puppeteer

3
推荐指数
1
解决办法
4371
查看次数

模板文字不适用于查询选择器

我正在循环浏览下拉列表,并尝试选择单个选项。如果我尝试使用模板文字,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)

为什么会发生这种情况?

javascript dom web-scraping puppeteer

3
推荐指数
1
解决办法
3206
查看次数