如果使用 setContent 加载页面,Puppeteer 将不会加载图像

Jur*_*els 3 javascript webautomation node.js puppeteer

我面临的问题是 Puppeteer 不加载使用相对路径指定的资源(例如background.png在 imagesrc或 css中url())。这样,我使用setContent()结果加载本地文件的内容与我执行相同操作但使用goto(file://).

显然,然后使用“setContent()”,页面停留在“about:page”,并阻止加载具有相对路径的资源。我想知道是否有任何方法可以指定文档位置并从字符串加载内容?

我会使用goto,但我需要先用 Handlebar 预处理 html。

现在,我执行以下操作:

    await page.goto(framePath);
    let content = await page.content();

    //Preprocess content here
    
    await page.setContent(processedContent);

Run Code Online (Sandbox Code Playgroud)

但感觉不太对劲,我想知道是否有更好的解决方案。

har*_*ded 6

setContent内部无非就是这个函数调用:

await this.evaluate(html => {
  document.open();
  document.write(html);
  document.close();
}, html);
Run Code Online (Sandbox Code Playgroud)

基本上,它在已加载的文档上写入 HTML。使用 goto 给出某个位置一点也不坏。您可以创建一个empty.html页面,并将其用作您自己定位的空白画布。