不能"document"对象作为参数传递给 page.exposeFunction



我正在使用这个库。构造函数Readability需要传递一个文档对象。

这是我想出的代码。

await page.exposeFunction('getReadability', (doc) => {
const article = new Readability(doc).parse();
return article;
});
const doc = await page.evaluate(() => {
const article = window.getReadability(document);
return article;
});

我犯了这样的错误。请注意,这只是错误消息的一个片段

error: Error: Evaluation failed: TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Window'
--- property 'parent' closes the circle
at JSON.stringify (<anonymous>)
at win.<computed> (<anonymous>:17:30)
at <anonymous>:2:28
at ExecutionContext._evaluateInternal (/home/chan-dev/Coding/serverSideJs/opengraph-scraper/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:217:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at ExecutionContext.evaluate (/home/chan-dev/Coding/serverSideJs/opengraph-scraper/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:106:16)
at _default (/home/chan-dev/Coding/serverSideJs/opengraph-scraper/helpers/link-previews.js:175:15)
at /home/chan-dev/Coding/serverSideJs/opengraph-scraper/src/index.js:45:16,
level: 'error',

此错误

var a = {};
a.b = a;

意味着您正试图序列化具有圆形结构的对象,例如:

PD_5你没有明确地序列化任何东西,但是。。。

正如这个答案所表明的,传递给puppeteer公开函数的对象必须是可序列化的。不幸的是,window和document都不可序列化(parent将不起作用,可能是因为document在某个地方引用了window,而window通过JSON.stringify(document)属性引用了它自己(。文档中似乎缺少此信息。

如果您打开控制台并键入document.documentElement.innerHTML,您将准确地看到您的错误,这意味着在后台的puppeteer会进行一些序列化,这对您的对象(文档(来说是不可能的。

作为替代方案,我可以建议通过$.load加载页面自己的HTML(https://www.w3schools.com/jquery/jquery_ajax_load.asp)或CCD_ 6属性,并将其作为字符串发送给Readability。

最新更新