# Puppeteer API ##### Table of Contents - [Puppeteer](#puppeteer) * [Emulation](#emulation) * [class: Browser](#class-browser) + [new Browser([options])](#new-browseroptions) + [browser.close()](#browserclose) + [browser.newPage()](#browsernewpage) + [browser.stderr](#browserstderr) + [browser.stdout](#browserstdout) + [browser.version()](#browserversion) * [class: Page](#class-page) + [event: 'console'](#event-console) + [event: 'dialog'](#event-dialog) + [event: 'frameattached'](#event-frameattached) + [event: 'framedetached'](#event-framedetached) + [event: 'framenavigated'](#event-framenavigated) + [event: 'load'](#event-load) + [event: 'pageerror'](#event-pageerror) + [event: 'request'](#event-request) + [event: 'requestfailed'](#event-requestfailed) + [event: 'requestfinished'](#event-requestfinished) + [event: 'response'](#event-response) + [page.$(selector, pageFunction, ...args)](#pageselector-pagefunction-args) + [page.$$(selector, pageFunction, ...args)](#pageselector-pagefunction-args) + [page.addScriptTag(url)](#pageaddscripttagurl) + [page.click(selector[, options])](#pageclickselector-options) + [page.close()](#pageclose) + [page.evaluate(pageFunction, ...args)](#pageevaluatepagefunction-args) + [page.evaluateOnNewDocument(pageFunction, ...args)](#pageevaluateonnewdocumentpagefunction-args) + [page.focus(selector)](#pagefocusselector) + [page.frames()](#pageframes) + [page.goBack(options)](#pagegobackoptions) + [page.goForward(options)](#pagegoforwardoptions) + [page.hover(selector)](#pagehoverselector) + [page.injectFile(filePath)](#pageinjectfilefilepath) + [page.keyboard](#pagekeyboard) + [page.mainFrame()](#pagemainframe) + [page.mouse](#pagemouse) + [page.navigate(url, options)](#pagenavigateurl-options) + [page.pdf(options)](#pagepdfoptions) + [page.plainText()](#pageplaintext) + [page.press(key[, options])](#pagepresskey-options) + [page.reload(options)](#pagereloadoptions) + [page.screenshot([options])](#pagescreenshotoptions) + [page.setContent(html)](#pagesetcontenthtml) + [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders) + [page.setInPageCallback(name, callback)](#pagesetinpagecallbackname-callback) + [page.setRequestInterceptor(interceptor)](#pagesetrequestinterceptorinterceptor) + [page.setUserAgent(userAgent)](#pagesetuseragentuseragent) + [page.setViewport(viewport)](#pagesetviewportviewport) + [page.title()](#pagetitle) + [page.type(text)](#pagetypetext) + [page.uploadFile(selector, ...filePaths)](#pageuploadfileselector-filepaths) + [page.url()](#pageurl) + [page.viewport()](#pageviewport) + [page.waitFor(selectorOrFunctionOrTimeout[, options])](#pagewaitforselectororfunctionortimeout-options) + [page.waitForFunction(pageFunction[, options, ...args])](#pagewaitforfunctionpagefunction-options-args) + [page.waitForNavigation(options)](#pagewaitfornavigationoptions) + [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) * [class: Keyboard](#class-keyboard) + [keyboard.down(key[, options])](#keyboarddownkey-options) + [keyboard.sendCharacter(char)](#keyboardsendcharacterchar) + [keyboard.up(key)](#keyboardupkey) * [class: Mouse](#class-mouse) + [mouse.click(x, y, [options])](#mouseclickx-y-options) + [mouse.down([options])](#mousedownoptions) + [mouse.move(x, y)](#mousemovex-y) + [mouse.up([options])](#mouseupoptions) * [class: Dialog](#class-dialog) + [dialog.accept([promptText])](#dialogacceptprompttext) + [dialog.dismiss()](#dialogdismiss) + [dialog.message()](#dialogmessage) + [dialog.type](#dialogtype) * [class: Frame](#class-frame) + [frame.$(selector, pageFunction, ...args)](#frameselector-pagefunction-args) + [frame.$$(selector, pageFunction, ...args)](#frameselector-pagefunction-args) + [frame.addScriptTag(url)](#frameaddscripttagurl) + [frame.childFrames()](#framechildframes) + [frame.click(selector[, options])](#frameclickselector-options) + [frame.evaluate(pageFunction, ...args)](#frameevaluatepagefunction-args) + [frame.focus(selector)](#framefocusselector) + [frame.hover(selector)](#framehoverselector) + [frame.injectFile(filePath)](#frameinjectfilefilepath) + [frame.isDetached()](#frameisdetached) + [frame.name()](#framename) + [frame.parentFrame()](#frameparentframe) + [frame.title()](#frametitle) + [frame.uploadFile(selector, ...filePaths)](#frameuploadfileselector-filepaths) + [frame.url()](#frameurl) + [frame.waitFor(selectorOrFunctionOrTimeout[, options])](#framewaitforselectororfunctionortimeout-options) + [frame.waitForFunction(pageFunction[, options, ...args])](#framewaitforfunctionpagefunction-options-args) + [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options) * [class: Request](#class-request) + [request.headers](#requestheaders) + [request.method](#requestmethod) + [request.postData](#requestpostdata) + [request.response()](#requestresponse) + [request.url](#requesturl) * [class: Response](#class-response) + [response.buffer()](#responsebuffer) + [response.headers](#responseheaders) + [response.json()](#responsejson) + [response.ok](#responseok) + [response.request()](#responserequest) + [response.status](#responsestatus) + [response.statusText](#responsestatustext) + [response.text()](#responsetext) + [response.url](#responseurl) * [class: InterceptedRequest](#class-interceptedrequest) + [interceptedRequest.abort()](#interceptedrequestabort) + [interceptedRequest.continue()](#interceptedrequestcontinue) + [interceptedRequest.headers](#interceptedrequestheaders) + [interceptedRequest.method](#interceptedrequestmethod) + [interceptedRequest.postData](#interceptedrequestpostdata) + [interceptedRequest.url](#interceptedrequesturl) ## Puppeteer Puppeteer is a Node library which provides a high-level API to control Chromium over the DevTools Protocol. Puppeteer provides a top-level require which has a [Browser](#class-browser) class. The following is a typical example of using a Browser class to drive automation: ```js const {Browser} = require('puppeteer'); const browser = new Browser(); browser.newPage().then(async page => { await page.navigate('https://google.com'); // other actions... browser.close(); }); ``` ### Emulation Puppeteer supports device emulation with two primitives: - [page.setUserAgent(userAgent)](#pagesetuseragentuseragent) - [page.setViewport(viewport)](#pagesetviewportviewport) To aid emulation, puppeteer provides a list of device descriptors which could be obtained via the `require('puppeteer/DeviceDescriptors')` command. Below is an example of emulating iPhone 6 in puppeteer: ```js const {Browser} = require('puppeteer'); const devices = require('puppeteer/DeviceDescriptors'); const iPhone = devices['iPhone 6']; const browser = new Browser(); browser.newPage().then(async page => { await Promise.all([ page.setUserAgent(iPhone.userAgent), page.setViewport(iPhone.viewport) ]); await page.navigate('https://google.com'); // other actions... browser.close(); }); ``` List of all available devices is available in the source code: [DeviceDescriptors.js](https://github.com/GoogleChrome/puppeteer/blob/master/DeviceDescriptors.js). ### class: Browser Browser manages a browser instance, creating it with a predefined settings, opening and closing pages. Instantiating Browser class does not necessarily result in launching browser; the instance will be launched when the need will arise. A typical scenario of using [Browser] is opening a new page and navigating it to a desired URL: ```js const {Browser} = require('puppeteer'); const browser = new Browser(); browser.newPage().then(async page => { await page.navigate('https://example.com'); browser.close(); }); ``` #### new Browser([options]) - `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - `headless` <[boolean]> Whether to run chromium in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). Defaults to `true`. - `executablePath` <[string]> Path to a chromium executable to run instead of bundled chromium. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). - `args` <[Array]<[string]>> Additional arguments to pass to the chromium instance. List of chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/). #### browser.close() Closes browser with all the pages (if any were opened). The browser object itself is considered to be disposed and could not be used anymore. #### browser.newPage() - returns: <[Promise]<[Page]>> Promise which resolves to a new [Page] object. #### browser.stderr - <[stream.Readable]> A Readable Stream that represents the browser process's stderr. For example, `stderr` could be piped into `process.stderr`: ```js const {Browser} = require('puppeteer'); const browser = new Browser(); browser.stderr.pipe(process.stderr); browser.version().then(version => { console.log(version); browser.close(); }); ``` #### browser.stdout - <[stream.Readable]> A Readable Stream that represents the browser process's stdout. For example, `stdout` could be piped into `process.stdout`: ```js const {Browser} = require('puppeteer'); const browser = new Browser(); browser.stdout.pipe(process.stdout); browser.version().then(version => { console.log(version); browser.close(); }); ``` #### browser.version() - returns: <[Promise]<[string]>> String describing browser version. For headless chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For non-headless, this is `Chrome/61.0.3153.0`. > **NOTE** the format of browser.version() is not fixed and might change with future releases of the library. ### class: Page Page provides methods to interact with browser page. Page could be thought about as a browser tab, so one [Browser] instance might have multiple [Page] instances. An example of creating a page, navigating it to a URL and saving screenshot as `screenshot.png`: ```js const {Browser} = require('puppeteer'); const browser = new Browser(); browser.newPage().then(async page => await page.navigate('https://example.com'); await page.screenshot({path: 'screenshot.png'}); browser.close(); }); ``` #### event: 'console' - <[string]> Emitted when a page calls one of console API methods, e.g. `console.log` or `console.dir`. If multiple arguments are passed over to the console API call, these arguments are dispatched in an event. An example of handling `console` event: ```js page.on('console', (...args) => { for (let i =0; i < args.length; ++i) console.log(`${i}: ${args[i]}`); }); page.evaluate(() => console.log(5, 'hello', {foo: 'bar'})); ``` #### event: 'dialog' - <[Dialog]> Emitted when a JavaScript dialog, such as `alert`, `prompt`, `confirm` or `beforeunload`, gets opened on the page. Puppeteer can take action to the dialog via dialog's [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods. #### event: 'frameattached' - <[Frame]> Emitted when a frame gets attached. #### event: 'framedetached' - <[Frame]> Emitted when a frame gets detached. #### event: 'framenavigated' - <[Frame]> Emitted when a frame committed navigation. #### event: 'load' Emitted when a page's `load` event was dispatched. #### event: 'pageerror' - <[string]> Emitted when an unhandled exception happens on the page. The only argument of the event holds the exception message. #### event: 'request' - <[Request]> Emitted when a page issues a request. The [request] object is a read-only object. In order to intercept and mutate requests, see [page.setRequestInterceptor](#pagesetrequestinterceptorinterceptor) #### event: 'requestfailed' - <[Request]> Emitted when a request is failed. #### event: 'requestfinished' - <[Request]> Emitted when a request is successfully finished. #### event: 'response' - <[Response]> Emitted when a [response] is received. #### page.$(selector, pageFunction, ...args) - `selector` <[string]> A [selector] to be matched in the page - `pageFunction` <[function]\([Element]\)> Function to be evaluated in-page with first element matching `selector` - `...args` <...[string]> Arguments to pass to `pageFunction` - returns: <[Promise]<[Object]>> Promise which resolves to function return value. Example: ```js const outerhtml = await page.$('#box', e => e.outerHTML); ``` Shortcut for [page.mainFrame().$(selector, pageFunction, ...args)](#pageselector-fun-args). #### page.$$(selector, pageFunction, ...args) - `selector` <[string]> A [selector] to be matched in the page - `pageFunction` <[function]\([Element]\)> Function to be evaluated in-page for every matching element. - `...args` <...[string]> Arguments to pass to `pageFunction` - returns: <[Promise]<[Array]<[Object]>>> Promise which resolves to array of function return values. Example: ```js const headings = await page.$$('h1,h2,h3,h4', el => el.textContent); for (const heading of headings) console.log(heading); ``` Shortcut for [page.mainFrame().$$(selector, pageFunction, ...args)](#pageselector-fun-args). #### page.addScriptTag(url) - `url` <[string]> Url of a script to be added - returns: <[Promise]> Promise which resolves as the script gets added and loads. Adds a `