如何将ElementHandle移动到另一个页面

问题描述 投票:1回答:1

我试图迭代一个ElementHandles数组并将它们附加到第二个页面,如下所示:

const htmlContent: string = `
    <html><head></head><body>
        <div class="section">Section 1</div>
        <div class="section">Section 2</div>
        <div class="main-container"></div>
    </body></html>`

let browser: Browser = await Puppeteer.launch();
const firstPage: Page = await browser.newPage();
const secondPage: Page = await browser.newPage();
await firstPage.goto('data:text/html;charset=UTF-8,' + htmlContent);
await secondPage.goto('data:text/html;charset=UTF-8,' + htmlContent);
let sections: ElementHandle[] = await firstPage.$$('.section');

for (const section of sections) {
    secondPage.$eval('.main-container', (el: any, section: ElementHandle) => {
        el.append(section);
    }, section);
}

browser.close()

我将此代码基于ElementHandle类的Puppeteer文档:

ElementHandle实例可以用作页面。$ eval()和page.evaluate()方法中的参数。

但是,这不起作用。它使用以下消息生成堆栈跟踪:

错误:只能在创建它们的上下文中评估JSHandles!

我尝试将该部分定义为any,并将JSHandle定义为相同的结果。我一直在搜索api文档中的任何提示,看看我做错了什么没有结果。

任何帮助,将不胜感激!

node.js typescript puppeteer
1个回答
0
投票

错误消息所引用的“上下文”是页面 - 您正在尝试将元素从一个页面复制到另一个页面,它根本不允许您这样做,并且遗憾的是,无法对它们进行序列化以便您可以传递它们。也就是说,只要丢失任何带外数据(例如事件监听器或JavaScript中设置的其他属性)是可以接受的,您可以复制outerHTML

const htmlContent: string = `
<html><head></head><body>
<div class="section">Section 1</div>
<div class="section">Section 2</div>
<div class="main-container"></div>
</body></html>`;

let browser: Browser = await Puppeteer.launch();
const firstPage: Page = await browser.newPage();
const secondPage: Page = await browser.newPage();
await firstPage.goto("data:text/html;charset=UTF-8," + htmlContent);
await secondPage.goto("data:text/html;charset=UTF-8," + htmlContent);
let sectionsAsHtml: string[] = await firstPage.$$eval(
  ".section",
  (elements: Element[]) => Array.from(elements).map(e => e.outerHTML)
);

for (const section of sectionsAsHtml) {
  await secondPage.$eval(".main-container", e => (e.innerHTML += section));
}

browser.close();
© www.soinside.com 2019 - 2024. All rights reserved.