How to load local files in Puppeteer?

You can load local files in Puppeteer by using the same page.goto method that you use for URLs, but you need to provide it with the file URL using the file protocol (file://). The file path must be an absolute path.

Here's some example code that opens a file located at /Users/yasoob/Desktop/ScrapingBee/index.html:

const puppeteer = require('puppeteer');

const filePath = 'file://'+'/Users/yasoob/Desktop/ScrapingBee/index.html';

async function loadLocalFile() {
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  await page.goto(filePath);
}

loadLocalFile();

It's important to note that loading local files in most browsers is subject to the same-origin policy, which means that the loaded file should come from the same origin as the web page running the JavaScript code. Additionally, it is important to make sure that the path being accessed is accessible by the running script. You can read more about these security implications in this StackOverflow answer.

Spinning up a local server and accessing local files using that can be a good alternative. This way you are not constraining yourself to the same origin policy.

Related Puppeteer web scraping questions: