暴露的函数 querySelector 在 Puppeteer 中不起作用 [英] Exposed function querySelector not working in Puppeteer
问题描述
document.querySelectorAll('.summary').innerText;
这会在下面的代码片段中引发错误,指出document.querySelector 不是函数";在我的 Puppeteer 页面的公开功能 docTest
中.
This throws an error in the below snippet saying "document.querySelector is not a function" in my Puppeteer page's exposed fucntion docTest
.
我想将特定节点传递给每个方法并在 evaluate
中获取结果.
I want to pass a specific node to each method and get the result inside evaluate
.
与 document.getElemnetbyId
相同.
const puppeteer = require('puppeteer');
//var querySelectorAll = require('query-selector');
let docTest = (document) => {
var summary = document.querySelectorAll(.summary).innerText;
console.log(summary);
return summary;
}
let scrape = async () => {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.goto('http://localhost.com:80/static.html');
await page.waitFor(5000)
await page.exposeFunction('docTest', docTest);
var result = await page.evaluate(() => {
var resultworking = document.querySelector("tr");
console.log(resultworking);
var summary = docTest(document);
console.log(resultworking);
return summary;
});
console.log(result);
await page.waitFor(7000);
browser.close();
return {
result
}
};
scrape().then((value) => {
console.log(value); // Success!
});
推荐答案
我刚刚遇到了同样的问题.问题是 page.evaluate()
函数回调必须是一个 async
函数并且你的函数 docTest()
将返回一个 Promise
在 page.evaluate()
内部调用时.要修复它,只需将 async
和 await
关键字添加到您的代码中:
I just had the same question. The problem is that the page.evaluate()
function callback has to be an async
function and your function docTest()
will return a Promise
when called inside the page.evaluate()
. To fix it, just add the async
and await
keywords to your code:
await page.exposeFunction('docTest', docTest);
var result = await page.evaluate(async () => {
var summary = await docTest(document);
console.log(summary);
return summary;
});
只要记住 page.exposeFunction()
会让你的函数返回一个 Promise
,然后,你需要使用 async
和 等待代码>.发生这种情况是因为您的函数不会在浏览器中运行,但在您的
nodejs
应用程序中.
Just remember that page.exposeFunction()
will make your function return a Promise
, then, you need to use async
and await
. This happens because your function will not be running inside your browser, but inside your nodejs
application.
- exposeFunction() 在 goto() 之后不起作用
- 为什么我无法访问 'window' 与 Puppeteer 一起使用 ExposeFunction() 函数?
- 如何使用evaluateOnNewDocument和exposeFunction?
- exposeFunction 保留在内存中?
- Puppeteer:在 .evaluate() 中传递变量
- Puppeteer 评估函数
- 允许将参数化函数作为字符串传递给 page.evaluate立>
- 与 page.exposeFunction() 绑定的函数会产生未处理的承诺拒绝
- 如何在 Puppeteers .evaluate() 中传递函数方法?
- 如何动态注入函数来评估使用傀儡师?
这篇关于暴露的函数 querySelector 在 Puppeteer 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!