Coder Social home page Coder Social logo

nightmare's Introduction

Build Status Nightmare

Nightmare is a high level wrapper for PhantomJS that lets you automate browser tasks.

The goal is to expose just a few simple methods, and have an API that feels synchronous for each block of scripting, rather than deeply nested callbacks. It's designed for automating tasks across sites that don't have APIs.

Examples

Let's search on Yahoo:

var Nightmare = require('nightmare');
new Nightmare()
  .goto('http://yahoo.com')
    .type('input[title="Search"]', 'github nightmare')
    .click('.searchsubmit')
    .run(function (err, nightmare) {
      if (err) return console.log(err);
      console.log('Done!');
    });

Or, let's extract the entirety of Kayak's home page after everything has rendered:

var Nightmare = require('nightmare');
new Nightmare()
  .goto('http://kayak.com')
  .evaluate(function () {
    return document.documentElement.innerHTML;
  }, function (res) {
    console.log(res);
  })
  .run();

Or, here's how you might automate a nicely abstracted login + task on Swiftly:

var Nightmare = require('nightmare');
var Swiftly = require('nightmare-swiftly');
new Nightmare()
  .use(Swiftly.login(email, password))
  .use(Swiftly.task(instructions, uploads, path))
  .run(function(err, nightmare){
    if (err) return fn(err);
    fn();
  });

And here's the nightmare-swiftly plugin.

API

new Nightmare(options)

Create a new instance that can navigate around the web.

The available options are:

  • timeout: how long to wait for page loads, default 5000ms
  • interval: how frequently to poll for page load state, default 50ms
  • port: port to mount the phantomjs instance to, default 12301
  • weak: set dnode weak option. For windows users, will fix cpp compilation issues. default true

.goto(url)

Load the page at url.

.back()

Go back to the previous page.

.forward()

Go forward to the next page.

.refresh()

Refresh the current page.

.url(cb)

Get the url of the current page, the signature of the callback is cb(url).

.title(cb)

Get the title of the current page, the signature of the callback is cb(title).

.click(selector)

Clicks the selector element once.

.type(selector, text)

Enters the text provided into the selector element.

.upload(selector, path)

Specify the path to upload into a file input selector element.

.inject(type, file)

Inject a local file onto the current page. The file type must be either 'js' or 'css'.

.evaluate(fn, cb, [arg1, arg2,...])

Invokes fn on the page with args. On completion it passes the return value of fn as to cb(res). Useful for extracting information from the page.

.wait()

Wait until a page finishes loading, typically after a .click().

.wait(ms)

Wait for ms milliseconds e.g. .wait(5000)

.wait(selector)

Wait until the element selector is present e.g. .wait('#pay-button')

.wait(fn, value, [delay])

Wait until the fn evaluated on the page returns value. Optionally, refresh the page every delay milliseconds, and only check after each refresh.

.screenshot(path)

Saves a screenshot of the current page to the specified path. Useful for debugging.

.useragent(useragent)

Set the useragent used by PhantomJS. You have to set the useragent before calling .goto().

.viewport(width, height)

Set the width and height of the viewport, useful for screenshotting. Weirdly, you have to set the viewport before calling .goto().

.on(event, callback)

Respond to page events with the callback. Supported events are:

  • initialized - callback()
  • loadStarted - callback()
  • loadFinished - callback(status)
  • urlChanged - callback(targetUrl)
  • navigationRequested - callback(url, type, willNavigate, main)
  • resourceRequested - callback(requestData, networkRequest)
  • resourceReceived - callback(response)
  • consoleMessage - callback(msg, lineNumber, sourceId)
  • alert - callback(msg)
  • confirm - callback(msg)
  • prompt - callback(msg, defaultValue)

For a more in depth description, see the full callbacks list for phantomjs.

.use(plugin)

Useful for using repeated code blocks, see the example with Swiftly login and task creation in the docs above.

.run(cb)

Executes the queue of functions, and calls your cb when the script hits an error or completes the queue. The callback signature is cb(err, nightmare).

Plugins

Here's a list of plugins, pull request to add your own to the list :)

Usage

Installation

Nightmare is a Node.js module, so you'll need to have Node.js installed. You'll also need to have phantomjs itself installed:

$ sudo brew update && brew install phantomjs
$ npm install --save nightmare

Alternatively, you can download Phantom JS from http://phantomjs.org

Execution

Nightmare is a node module that can be used in a Node.js script or module. Here's a simple script to open a web page:

var Nightmare = require('nightmare');
var nightmare = new Nightmare();
nightmare
  .goto('http://kayak.com')
  .run(function(err, nightmare){
    console.log('Done.');
  });

If you save this as kayak.js, you can run it on the command line like this: node kayak.js.

Debug

To run the same file with debugging output, run it like this DEBUG=nightmare node kayak.js.

This will print out some additional information about what's going on:

nightmare queueing action "goto" +0ms
  nightmare run +3ms
  nightmare .setup() creating phantom instance on port 12301 +1ms
  nightmare .setup() phantom instance created +145ms
  nightmare .setup() phantom page created +4ms
  nightmare .goto() url: http://kayak.com +2ms
  nightmare .goto() page loaded: success +1s
  nightmare .teardownInstance() tearing down and bumping port to 12302 +501ms
Done.

Tests

Automated tests for nightmare itself are run using Mocha and Should, both of which will be installed via npm install. To run nightmare's tests, just do make test.

When the tests are done, you'll see something like this:

make test
  ․․․․․․․․․․․․․․․․․
  28 passing (46s)

License (MIT)

WWWWWW||WWWWWW
 W W W||W W W
      ||
    ( OO )__________
     /  |           \
    /o o|    MIT     \
    \___/||_||__||_|| *
         || ||  || ||
        _||_|| _||_||
       (__|__|(__|__|

Copyright (c) 2014 Segment.io Inc. [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

nightmare's People

Contributors

evanhahn avatar lambtron avatar queckezz avatar reinpk avatar securingsincity avatar stevenschobert avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.