Commit 96fc2436 96fc243672d7b0b912cd7a88464f21b16bdc3c1d by Nicolas Perriault

added samples repository

1 parent bebd54d8
1 phantom.injectJs('casper.js');
2
3 var logo;
4
5 new phantom.Casper({
6 verbose: true
7 }).start('http://www.google.fr/', function(self) {
8 // download the google logo image as base64
9 logo = self.base64encode('http://www.google.fr/images/srpr/logo3w.png', 'google_logo.png');
10 }).run(function(self) {
11 self.echo(logo).exit();
12 });
1 phantom.injectJs("casper.js");
2
3 var articles = [];
4
5 /**
6 * Adds two new methods to the Casper prototype: fetchTexts and renderJSON.
7 */
8 phantom.Casper.extend({
9 /**
10 * Adds a new navigation step for casper; basically it will:
11 *
12 * 1. open an url,
13 * 2. on loaded, will fetch all contents retrieved through the provided
14 * CSS3 selector and return them in a formatted object.
15 */
16 fetchTexts: function(location, selector) {
17 return this.thenOpen(location, function(self) {
18 var texts = self.evaluate(function() {
19 var elements = document.querySelectorAll('%selector%');
20 return Array.prototype.map.call(elements, function(e) {
21 return e.innerText;
22 });
23 }, {
24 selector: selector.replace("'", "\'")
25 });
26 articles = articles.concat(texts);
27 });
28 },
29
30 /**
31 * Echoes a JSON output of the fetched results and exits phantomjs.
32 */
33 renderJSON: function(what) {
34 return this.echo(JSON.stringify(what, null, ' ')).exit();
35 }
36 });
37
38 var casper = new phantom.Casper({
39 loadImages: false,
40 loadPlugins: false,
41 logLevel: "debug",
42 verbose: true,
43 });
44
45 casper.start()
46 .fetchTexts('http://www.liberation.fr/', 'h3') // all article titles are stored in <h3>
47 .fetchTexts('http://www.lemonde.fr/', 'h2.article') // all article titles are stored in <h2 class="article">
48 .run(function(self) {
49 self.renderJSON(articles);
50 })
51 ;
1 phantom.injectJs('casper.js');
2
3 function getLinks() {
4 var links = document.querySelectorAll('h3.r a');
5 return Array.prototype.map.call(links, function(e) {
6 return {
7 title: e.innerText,
8 href: e.getAttribute('href')
9 };
10 });
11 }
12
13 var links = [];
14 var casper = new phantom.Casper({
15 logLevel: "debug",
16 loadImages: false,
17 loadPlugins: false,
18 verbose: true
19 })
20 .start('http://google.fr/')
21 .then(function(self) {
22 // search for 'casperjs' from google form
23 self.fill('form[name=f]', {
24 q: 'casperjs'
25 }, true);
26 })
27 .then(function(self) {
28 // aggregate results for the 'casperjs' search
29 links = self.evaluate(getLinks);
30 // now search for 'phantomjs' by fillin the form again
31 self.fill('form[name=f]', {
32 q: 'phantomjs'
33 }, true);
34 })
35 .then(function(self) {
36 // aggregate results for the 'phantomjs' search
37 links = links.concat(self.evaluate(getLinks));
38 })
39 .run(function(self) {
40 // echo results in some pretty fashion
41 self.echo(links.map(function(i) {
42 return i.title + ' (' + i.href + ')';
43 }).join('\n')).exit();
44 })
45 ;