exposed function queryseldtcor not working in puppeteer

半腔热情 提交于 2020-05-22 07:39:36

问题


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.

  1. exposeFunction() does not work after goto()
  2. Why can't I access 'window' in an exposeFunction() function with Puppeteer?
  3. How to use evaluateOnNewDocument and exposeFunction?
  4. exposeFunction remains in memory?
  5. Puppeteer: pass variable in .evaluate()
  6. Puppeteer evaluate function
  7. allow to pass a parameterized funciton as a string to page.evaluate
  8. Functions bound with page.exposeFunction() produce unhandled promise rejections
  9. How to pass a function in Puppeteers .evaluate() method?
  10. How can I dynamically inject functions to evaluate using Puppeteer?


来源:https://stackoverflow.com/questions/58772855/exposed-function-queryseldtcor-not-working-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!