使用Puppeteer打开本地HTML文件 [英] Opening local HTML file using Puppeteer

查看:1411
本文介绍了使用Puppeteer打开本地HTML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Puppeteer(无Web服务器)使用无头Chrome打开本地HTML文件?我只能让它在本地服务器上工作.

Is it possible to open a local HTML file with headless Chrome using Puppeteer (without a web server)? I could only get it to work against a local server.

我在setContent()和goto() > Puppeteer API文档,但是:

I found setContent() and goto() in the Puppeteer API documentation, but:

  1. page.goto:不适用于本地文件或file://.
  2. page.setContent:用于HTML字符串
  1. page.goto: did not work with a local file or file://.
  2. page.setContent: is for an HTML string

推荐答案

我只是在本地进行了一次测试(您可以看到我在Windows上进行了此测试),并且puppeteer使用page.goto和完整的文件网址愉快地打开了我的本地html文件. ,并将其另存为pdf:

I just did a test locally (you can see I did this on windows) and puppeteer happily opened my local html file using page.goto and a full file url, and saved it as a 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();    
})();

如果您需要使用相对路径,则可能需要查看有关使用相对文件路径的问题:

If you need to use a relative path might want to look at this question about the use of relative file paths: File Uri Scheme and Relative Files

这篇关于使用Puppeteer打开本地HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆