问题
document.querySelectorAll('.summary').innerText;
this throws error in below snippet saying "document.querySelector is not a function" in my puppeteer page's exposed fucntion "docTest" i want to pass specific node to each method and get the result insde the evaluate.
same with document.getElemenetbyId
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!
});
回答1:
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;
});
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() does not work after goto()
- Why can't I access 'window' in an exposeFunction() function with Puppeteer?
- How to use evaluateOnNewDocument and exposeFunction?
- exposeFunction remains in memory?
- Puppeteer: pass variable in .evaluate()
- Puppeteer evaluate function
- allow to pass a parameterized funciton as a string to page.evaluate
- Functions bound with page.exposeFunction() produce unhandled promise rejections
- How to pass a function in Puppeteers .evaluate() method?
- How can I dynamically inject functions to evaluate using Puppeteer?
来源:https://stackoverflow.com/questions/58772855/exposed-function-queryseldtcor-not-working-in-puppeteer