Opening local html file using puppeteer

你说的曾经没有我的故事 提交于 2019-11-30 13:43:05

问题


Is it possible to open local html file with headless chrome using puppeteer (without web server)? I could only gate it to work against local server.

I could see setContent() api and goto() api and

  1. page.goto: did not work with local file or file:// too.
  2. page.setContent: is for html string

回答1:


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




回答2:


If file is on local, using setContent will be better than goto

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

You can check performance between setContent and goto at here




回答3:


Why not open the HTML file read the content, then "setContent"




回答4:


I open the file I wanted to load into the browser and copied the URL to make sure all the \'s where correct.

await page.goto(`file:///C:/pup_scrapper/testpage/TM.html`);



回答5:


Navigation to local files only works if you also pass a referer of file://, otherwise security restrictions prevent this from succeeding.



来源:https://stackoverflow.com/questions/47587352/opening-local-html-file-using-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!