Blame view

docs/quickstart.rst 5.89 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
.. _quickstart:

==========
Quickstart
==========

Once CasperJS is :doc:`properly installed <installation>`, you can write your first script. You can use plain :ref:`Javascript <quickstart_javascript>` or :ref:`CoffeeScript <quickstart_coffeescript>`.

.. hint::

   If you're not too comfortable with Javascript, a :ref:`dedicated FAQ entry <faq_javascript>` is waiting for you.

.. _quickstart_javascript:

A minimal scraping script
-------------------------

Fire up your favorite editor, create and save a ``sample.js`` file like below::

    var casper = require('casper').create();

    casper.start('http://casperjs.org/', function() {
        this.echo(this.getTitle());
    });

    casper.thenOpen('http://phantomjs.org', function() {
        this.echo(this.getTitle());
    });

    casper.run();

Run it:

.. code-block:: text

    $ casperjs sample.js

You should get something like this:

.. code-block:: text

    $ casperjs c.js
    CasperJS, a navigation scripting and testing utility for PhantomJS | CasperJS 1.0.0
    PhantomJS: Headless WebKit with JavaScript API

.. topic:: What did we just do?

   1. we created a new :ref:`Casper <casper_module>` instance
   2. we started it and opened ``http://casperjs.org/``
   3. *once* the page has been loaded, we asked to print the title of that webpage (the content of its ``<title>`` tag)
   4. *then* we opened another url, ``http://phantomjs.org/``
   5. *once* the new page has been loaded, we asked to print its title too
   6. we executed the whole process


Now let's scrape Google!
------------------------

In the following example, we'll query google for two terms consecutively, *"casperjs"* and *"phantomjs"*, aggregate the result links in a standard ``Array`` and output the result to the console.

Fire up your favorite editor and save the javascript code below in a
``googlelinks.js`` file::

    var links = [];
    var casper = require('casper').create();

    function getLinks() {
        var links = document.querySelectorAll('h3.r a');
        return Array.prototype.map.call(links, function(e) {
            return e.getAttribute('href')
        });
    }

    casper.start('http://google.fr/', function() {
        // search for 'casperjs' from google form
        this.fill('form[action="/search"]', { q: 'casperjs' }, true);
    });

    casper.then(function() {
        // aggregate results for the 'casperjs' search
        links = this.evaluate(getLinks);
        // now search for 'phantomjs' by filling the form again
        this.fill('form[action="/search"]', { q: 'phantomjs' }, true);
    });

    casper.then(function() {
        // aggregate results for the 'phantomjs' search
        links = links.concat(this.evaluate(getLinks));
    });

    casper.run(function() {
        // echo results in some pretty fashion
        this.echo(links.length + ' links found:');
        this.echo(' - ' + links.join('\n - ')).exit();
    });

Run it:

.. code-block:: text

    $ casperjs googlelinks.js
    20 links found:
     - https://github.com/n1k0/casperjs
     - https://github.com/n1k0/casperjs/issues/2
     - https://github.com/n1k0/casperjs/tree/master/samples
     - https://github.com/n1k0/casperjs/commits/master/
     - http://www.facebook.com/people/Casper-Js/100000337260665
     - http://www.facebook.com/public/Casper-Js
     - http://hashtags.org/tag/CasperJS/
     - http://www.zerotohundred.com/newforums/members/casper-js.html
     - http://www.yellowpages.com/casper-wy/j-s-enterprises
     - http://local.trib.com/casper+wy/j+s+chinese+restaurant.zq.html
     - http://www.phantomjs.org/
     - http://code.google.com/p/phantomjs/
     - http://code.google.com/p/phantomjs/wiki/QuickStart
     - http://svay.com/blog/index/post/2011/08/31/Paris-JS-10-%3A-Introduction-%C3%A0-PhantomJS
     - https://github.com/ariya/phantomjs
     - http://dailyjs.com/2011/01/28/phantoms/
     - http://css.dzone.com/articles/phantom-js-alternative
     - http://pilvee.com/blog/tag/phantom-js/
     - http://ariya.blogspot.com/2011/01/phantomjs-minimalistic-headless-webkit.html
     - http://www.readwriteweb.com/hack/2011/03/phantomjs-the-power-of-webkit.php


.. _quickstart_coffeescript:

.. index:: coffeescript

CoffeeScript version
--------------------

You can also write Casper scripts using the `CoffeeScript syntax <http://jashkenas.github.com/coffee-script/>`_:

.. code-block:: coffeescript

    getLinks = ->
      links = document.querySelectorAll "h3.r a"
      Array::map.call links, (e) -> e.getAttribute "href"

    links = []
    casper = require('casper').create()

    casper.start "http://google.fr/", ->
      # search for 'casperjs' from google form
      @fill "form[action='/search']", q: "casperjs", true

    casper.then ->
      # aggregate results for the 'casperjs' search
      links = @evaluate getLinks
      # search for 'phantomjs' from google form
      @fill "form[action='/search']", q: "phantomjs", true

    casper.then ->
      # concat results for the 'phantomjs' search
      links = links.concat @evaluate(getLinks)

    casper.run ->
      # display results
      @echo links.length + " links found:"
      @echo(" - " + links.join("\n - ")).exit()

Just remember to suffix your script with the ``.coffee`` extension.

A minimal testing script
------------------------

CasperJS is also a :ref:`testing framework <testing>`; test scripts are slightly different than scraping ones, though they share most of their API. A simplest test script::

    // hello-test.js
    casper.test.assert(true);
    casper.test.done();

Run it using the ``casperjs test`` subcommand:

.. code-block:: text

    $ casperjs test hello-test.js
    Test file: hello-test.js
    PASS Subject is strictly true
    PASS 1 tests executed in 0.103s, 1 passed, 0 failed.

.. note::

   As you can see, there's no need to create a ``casper`` instance in a test script as a preconfigured one has already made available for you.

   You can read more about testing in the :ref:`dedicated section <testing>`.