使用puppeteer打开本地html文件

Ani*_*mde 19 automation unit-testing google-chrome puppeteer

是否可以使用puppeteer(没有Web服务器)使用无头chrome打开本地html文件?我只能将它连接到本地服务器.

我可以看到setContent()api和goto()api

  1. page.goto:无法使用本地文件或file://.
  2. page.setContent:用于html字符串

com*_*eye 17

我刚刚在本地做了一个测试(你可以看到我在windows上做了这个),而puppeteer使用page.goto和一个完整的文件URL愉快地打开我的本地html文件,并将其保存为pdf:

'use strict';

const puppeteer = require('puppeteer');    
(async() => {    
const browser = await puppeteer.launch();
const page = await browser.newPage();    
await page.goto('file://C:/Users/compoundeye/test.html');    
await page.pdf({
  path: 'test.pdf',
  format: 'A4',
  margin: {
        top: "20px",
        left: "20px",
        right: "20px",
        bottom: "20px"
  }    
});    
await browser.close();    
})();
Run Code Online (Sandbox Code Playgroud)

如果您需要使用相对路径,可能需要查看有关相对文件路径的使用的问题:File Uri Scheme和Relative Files

  • `await page.goto(\`file:$ {path.join(__ dirname,'test.html')} \`);`看起来好多了 (20认同)
  • 如果你像我一样是 Node.js 菜鸟,请不要忘记在之前定义路径:`const path = require('path');` (3认同)
  • 如果你像我一样是一个 Node.js 菜鸟,但你在你的项目中使用新的 es6 功能 `import * as path from 'path'` [试图变得有趣,让世界更快乐:)] (3认同)

Chu*_*ran 11

如果文件位于本地,则使用setContent优于goto

var contentHtml = fs.readFileSync('file://C:/Users/compoundeye/test.html', 'utf8');
await page. setContent(contentHtml);    
Run Code Online (Sandbox Code Playgroud)

您可以在此处检查setContentgoto之间的性能


Bob*_*ski 7

为什么不打开HTML文件读取内容,然后“setContent”

  • 其他方式```javascript await page.goto(`data:text/html,${pageHtml}`, { waitUntil: 'networkidle0' }); `` (3认同)

moe*_*fju 7

导航到本地文件仅在您还传递 的引用时才有效file://,否则安全限制会阻止此操作成功。


Mic*_*zos 6

我们以本地 HTML 文件中的元素截图为例

import puppeteer from 'puppeteer';


(async () => {

    const browser = await puppeteer.launch();

    const page = await browser.newPage();
    
    //  __dirname is a global node variable that corresponds to the absolute 
    // path of the folder containing the currently executing file
    await page.goto(`file://${__dirname}/pages/test.html`);

    const element = await page.$('.myElement');

    if (element) {
        await elementHandle.screenshot({
            path: `./out/screenshot.png`,
            omitBackground: true,
        });
    }

    await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)