简体   繁体   中英

How to run Google Chrome Headless Puppeteer code

I am trying to use puppeteer (specifically to take a screenshot after a delay , but my problem is more basic than that)

https://github.com/GoogleChrome/puppeteer

I have run the following commands successfully.

sudo apt-get install npm
sudo apt-get install node
npm i puppeteer

The documentation says the following

Puppeteer will be familiar to people using other browser testing frameworks. You create an instance of Browser, open pages, and then manipulate them with Puppeteer's API.

Unfortunately I am not familiar with other browser testing frameworks, and I do not know what they mean by "create an instance of Browser".

I see the examples/screenshot.js file. It contains the following.

'use strict';

const puppeteer = require('puppeteer');

(async() => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://example.com');
await page.screenshot({path: 'example.png'});

await browser.close();

})();

I don't see mentioned in any README, documentation, or Q&A on how to run this code. Everything seems to assume that this step is obvious, which it might be but I'm at a loss as I'm not terribly familiar with Node.

  • I have called node examples/screenshot.js , but the terminal doesn't give any feedback and the image isn't created in any path I specify. Permissions are correct.

  • I tried calling node install.js first as well.

  • I have tried running the script inline directly in the terminal, but that gives "unexpected token (" in terminal.

  • I have even tried running it in the browser. Obviously that didn't work.

How do I run puppeteer code?

node.js version that you have installed via apt are probably rather older/stable.

puppeteer requires the newer node.js (7.6+) that supports async/await functions, here's a simple way to install it at the time of writing: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

You then indeed run the example script by issuing command

node examples/screenshot.js

and the screenshot should be in the directory from where ytou ran the command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM