Commit 329b0b7e 329b0b7e89fac11701becaaef5bda79e3af1e37d by Nicolas Perriault

ported all samples to coffeescript

1 parent 218f7652
...@@ -74,7 +74,7 @@ if (!phantom.casperLoaded) { ...@@ -74,7 +74,7 @@ if (!phantom.casperLoaded) {
74 phantom.sourceIds = {}; 74 phantom.sourceIds = {};
75 75
76 phantom.getErrorMessage = function(e) { 76 phantom.getErrorMessage = function(e) {
77 return (e.fileName || phantom.sourceIds[e.sourceId]) + ':' + e.line + ' ' + e; 77 return (e.fileName || this.sourceIds[e.sourceId]) + ':' + e.line + ' ' + e;
78 }; 78 };
79 79
80 phantom.getScriptCode = function(file, onError) { 80 phantom.getScriptCode = function(file, onError) {
...@@ -83,7 +83,7 @@ if (!phantom.casperLoaded) { ...@@ -83,7 +83,7 @@ if (!phantom.casperLoaded) {
83 try { 83 try {
84 scriptCode = CoffeeScript.compile(scriptCode); 84 scriptCode = CoffeeScript.compile(scriptCode);
85 } catch (e) { 85 } catch (e) {
86 phantom.processScriptError(e, file, onError); 86 this.processScriptError(e, file, onError);
87 } 87 }
88 } 88 }
89 // trick to locate source file location on error 89 // trick to locate source file location on error
...@@ -94,8 +94,8 @@ if (!phantom.casperLoaded) { ...@@ -94,8 +94,8 @@ if (!phantom.casperLoaded) {
94 }; 94 };
95 95
96 phantom.processScriptError = function(error, file, callback) { 96 phantom.processScriptError = function(error, file, callback) {
97 if (!phantom.sourceIds.hasOwnProperty(error.sourceId)) { 97 if (!this.sourceIds.hasOwnProperty(error.sourceId)) {
98 phantom.sourceIds[error.sourceId] = file; 98 this.sourceIds[error.sourceId] = file;
99 } 99 }
100 if (error.message === "__sourceId__") { 100 if (error.message === "__sourceId__") {
101 return; 101 return;
...@@ -103,8 +103,8 @@ if (!phantom.casperLoaded) { ...@@ -103,8 +103,8 @@ if (!phantom.casperLoaded) {
103 if (typeof callback === "function") { 103 if (typeof callback === "function") {
104 callback(error, file); 104 callback(error, file);
105 } else { 105 } else {
106 console.error(phantom.getErrorMessage(error)); 106 console.error(this.getErrorMessage(error));
107 phantom.exit(1); 107 this.exit(1);
108 } 108 }
109 }; 109 };
110 110
...@@ -194,7 +194,7 @@ if (!phantom.casperLoaded) { ...@@ -194,7 +194,7 @@ if (!phantom.casperLoaded) {
194 }); 194 });
195 } 195 }
196 196
197 // BC 197 // BC < 0.6
198 phantom.Casper = require('casper').Casper; 198 phantom.Casper = require('casper').Casper;
199 199
200 // casper cli args 200 // casper cli args
......
1 """ A basic custom logging implementation. The idea is to (extremely) verbosely
2 log every received resource.
3 """
4
5 casper = require('casper').create
6 # Every time a resource is received, a new log entry is added to the stack
7 # at the 'verbose' level.
8 onResourceReceived: (self, resource) ->
9 infos = []
10 props = ["url", "status", "statusText", "redirectURL", "bodySize"]
11 infos.push resource[prop] for prop in props
12 infos.push "[#{h.name}: #{h.value}]" for h in resource.headers
13 @log infos.join(', '), 'verbose'
14 verbose: true # we want to see the log printed out to the console
15 logLevel: 'verbose' # of course we want to see logs to our new level :)
16
17
18 # add a new 'verbose' logging level at the lowest priority
19 casper.logLevels = ['verbose'].concat casper.logLevels
20
21 # test our new logger with google
22 casper.start 'http://www.google.com/'
23 casper.run()
1 # download the google logo image as base64
2
3 casper = require('casper').create verbose: true
4
5 casper.start 'http://www.google.fr/', ->
6 @echo @base64encode 'http://www.google.fr/images/srpr/logo3w.png'
7
8 casper.run()
...\ No newline at end of file ...\ No newline at end of file
1 var logo; 1 // download the google logo image as base64
2 2
3 var casper = require('casper').create({ 3 var casper = require('casper').create({
4 verbose: true 4 verbose: true
5 }); 5 });
6 6
7 casper.start('http://www.google.fr/', function(self) { 7 casper.start('http://www.google.fr/', function(self) {
8 // download the google logo image as base64 8 self.echo(self.base64encode('http://www.google.fr/images/srpr/logo3w.png'));
9 logo = self.base64encode('http://www.google.fr/images/srpr/logo3w.png');
10 }); 9 });
11 10
12 casper.run(function(self) { 11 casper.run();
13 self.echo(logo).exit();
14 });
......
1 casper = require('casper').create verbose: true
2
3 # If we don't set a limit, it could go on forever
4 upTo = ~~casper.cli.get(0) || 10 # max 10 links
5
6 # Fetch all <a> elements from the page and return
7 # the ones which contains a href starting with 'http://'
8 searchLinks = ->
9 filter = Array::filter
10 map = Array::map
11 links = document.querySelectorAll 'a'
12 absolutes = filter.call links, (a) ->
13 /^http:\/\/.*/i.test a.getAttribute 'href'
14 return map.call absolutes, (a) -> a.getAttribute 'href'
15
16 # The base links array
17 links = [
18 'http://google.com/'
19 'http://yahoo.com/'
20 'http://bing.com/'
21 ]
22
23 # Just opens the page and prints the title
24 start = (link) -> @start link, -> @echo "Page title: #{ @getTitle() }"
25
26 # Get the links, and add them to the links array
27 # (It could be done all in one step, but it is intentionally splitted)
28 addLinks = (link) ->
29 @then ->
30 found = @evaluate searchLinks
31 @echo "#{found.length} links found on #{link}"
32 links = links.concat found
33
34 casper.start()
35
36 casper.then -> @echo 'Starting'
37
38 currentLink = 0;
39
40 # As long as it has a next link, and is under the maximum limit, will keep running
41 check = ->
42 if links[currentLink] && currentLink < upTo
43 @echo "--- Link #{currentLink} ---"
44 start.call @, links[currentLink]
45 addLinks.call @, links[currentLink]
46 currentLink++
47 @run check
48 else
49 @echo 'All done.'
50 @exit()
51
52 casper.run check
...@@ -14,7 +14,7 @@ var upTo = ~~casper.cli.get(0) || 10; // max 10 links ...@@ -14,7 +14,7 @@ var upTo = ~~casper.cli.get(0) || 10; // max 10 links
14 // the ones which contains a href starting with 'http://' 14 // the ones which contains a href starting with 'http://'
15 function searchLinks() { 15 function searchLinks() {
16 var filter = Array.prototype.filter, 16 var filter = Array.prototype.filter,
17 map = Array.prototype.map; 17 map = Array.prototype.map;
18 return map.call(filter.call(document.querySelectorAll('a'), function(a) { 18 return map.call(filter.call(document.querySelectorAll('a'), function(a) {
19 return (/^http:\/\/.*/i).test(a.getAttribute('href')); 19 return (/^http:\/\/.*/i).test(a.getAttribute('href'));
20 }), function(a) { 20 }), function(a) {
......
1 casper = require('casper').create()
2
3 links = [
4 'http://google.com/'
5 'http://yahoo.com/'
6 'http://bing.com/'
7 ]
8
9 casper.start()
10
11 casper.each links, (self, link) ->
12 @thenOpen link, -> @echo "#{@getTitle()} - #{link}"
13
14 casper.run()
1 var casper = require('casper').create();
2
1 var links = [ 3 var links = [
2 'http://google.com/', 4 'http://google.com/',
3 'http://yahoo.com/', 5 'http://yahoo.com/',
4 'http://bing.com/' 6 'http://bing.com/'
5 ]; 7 ];
6 8
7 var casper = require('casper').create();
8
9 casper.start().each(links, function(self, link) { 9 casper.start().each(links, function(self, link) {
10 self.thenOpen(link, function(self) { 10 self.thenOpen(link, function(self) {
11 self.echo(self.getTitle()); 11 self.echo(self.getTitle() + ' - ' + link);
12 }); 12 });
13 }); 13 });
14 14
......
1 articles = []
2 CasperClass = require('casper').Casper
3
4 ###
5 Adds two new methods to the Casper prototype: fetchTexts and renderJSON.
6 ###
7 CasperClass.extend
8 # Adds a new navigation step for casper; basically it will:
9 #
10 # 1. open an url,
11 # 2. on loaded, will fetch all contents retrieved through the provided
12 # CSS3 selector and return them in a formatted object.
13 fetchTexts: (location, selector) ->
14 @thenOpen location, ->
15 fetch = (selector) ->
16 elements = document.querySelectorAll(selector)
17 Array::map.call elements, (e) -> e.innerText
18 texts = @evaluate fetch, selector: selector
19 articles = articles.concat texts
20
21 # Echoes a JSON output of the fetched results and exits phantomjs.
22 renderJSON: (what) ->
23 @echo JSON.stringify what, null, ' '
24 @exit()
25
26 casper = new CasperClass
27 loadImages: false
28 loadPlugins: false
29 logLevel: "debug"
30 verbose: true
31
32 casper.start()
33
34 # all article titles are stored in <h3>
35 casper.fetchTexts 'http://www.liberation.fr/', 'h3'
36
37 # all article titles are stored in <h2 class="article">
38 casper.fetchTexts 'http://www.lemonde.fr/', 'h2.article'
39
40 casper.run -> @renderJSON articles
1 getLinks = ->
2 links = document.querySelectorAll "h3.r a"
3 Array::map.call links, (e) -> e.getAttribute "href"
4
5 links = []
6 casper = require('casper').create()
7
8 casper.start "http://google.fr/", ->
9 # search for 'casperjs' from google form
10 @fill "form[name=f]", q: "casperjs", true
11
12 casper.then ->
13 # aggregate results for the 'casperjs' search
14 links = @evaluate getLinks
15 # search for 'phantomjs' from google form
16 @fill "form[name=f]", q: "phantomjs", true
17
18 casper.then ->
19 # concat results for the 'phantomjs' search
20 links = links.concat @evaluate(getLinks)
21
22 casper.run ->
23 # display results
24 @echo "#{links.length} links found:"
25 @echo " - " + links.join "\n - "
26 @exit()
...\ No newline at end of file ...\ No newline at end of file
1 ###
2 Takes provided terms passed as arguments and query google for the number of
3 estimated results each have.
4
5 Usage:
6 $ casperjs samples/googlematch.js nicolas chuck borris
7 nicolas: 69600000
8 chuck: 49500000
9 borris: 2370000
10 winner is "nicolas" with 69600000 results
11 ###
12
13 CasperClass = require('casper').Casper
14
15 CasperClass.extend
16 fetchScore: -> @evaluate ->
17 result = document.querySelector('#resultStats').innerText
18 ~~(/Environ ([0-9\s]{1,}).*/.exec(result)[1].replace(/\s/g, ''))
19
20 casper = new CasperClass verbose: true
21
22 terms = casper.cli.args # terms are passed through command-line arguments
23
24 if terms.length < 3
25 casper.echo 'Usage: casperjs googlematch.js term1, term2 [, term3]...'
26 casper.exit()
27
28 scores = []
29
30 casper.echo "Let the match begin between \"#{terms.join '", "'}\"!"
31
32 casper.start "http://google.fr/"
33
34 casper.each terms, (self, term) ->
35 @then -> @fill 'form[name=f]', { q: term }, true
36 @then ->
37 score = @fetchScore()
38 scores.push term: term, score: score
39 self.echo "#{term}: #{score}"
40
41 casper.run ->
42 scores.sort -> (a, b) -> b.score > a.score
43 winner = scores[0]
44 @echo "Winner is #{winner.term} with #{winner.score} results"
45 @exit()
...@@ -15,7 +15,7 @@ CasperClass.extend({ ...@@ -15,7 +15,7 @@ CasperClass.extend({
15 fetchScore: function() { 15 fetchScore: function() {
16 return this.evaluate(function() { 16 return this.evaluate(function() {
17 var result = document.querySelector('#resultStats').innerText; 17 var result = document.querySelector('#resultStats').innerText;
18 return Number(/Environ ([0-9\s]{1,}).*/.exec(result)[1].replace(/\s/g, '')); 18 return ~~(/Environ ([0-9\s]{1,}).*/.exec(result)[1].replace(/\s/g, ''));
19 }); 19 });
20 } 20 }
21 }); 21 });
...@@ -47,9 +47,9 @@ casper.each(terms, function(self, term, i) { ...@@ -47,9 +47,9 @@ casper.each(terms, function(self, term, i) {
47 47
48 casper.run(function(self) { 48 casper.run(function(self) {
49 scores.sort(function(a, b) { 49 scores.sort(function(a, b) {
50 return a.score - b.score; 50 return b.score > a.score;
51 }); 51 });
52 var winner = scores[scores.length - 1]; 52 var winner = scores[0];
53 self.echo('winner is "' + winner.term + '" with ' + winner.score + ' results'); 53 self.echo('winner is "' + winner.term + '" with ' + winner.score + ' results');
54 self.exit(); 54 self.exit();
55 }); 55 });
......
1 casper = require('casper').create logLevel: "debug"
2
3 casper.start 'http://www.google.fr/', ->
4 @test.assertTitle 'Google', 'google homepage title is the one expected'
5 @test.assertExists 'form[name=f]', 'main form is found'
6 @fill 'form[name=f]', q: 'foo', true
7
8 casper.then ->
9 @test.assertTitle 'foo - Recherche Google', 'google title is ok'
10 @test.assertUrlMatch /q=foo/, 'search term has been submitted'
11 test = -> __utils__.findAll('h3.r').length >= 10
12 @test.assertEval test, 'google search for "foo" retrieves 10 or more results'
13
14 casper.run -> @test.renderResults true
1 casper = require('casper').create verbose: true, logLevel: 'debug'
2
3 casper.log 'this is a debug message', 'debug'
4 casper.log 'and an informative one', 'info'
5 casper.log 'and a warning', 'warning'
6 casper.log 'and an error', 'error'
7
8 casper.exit()
1 casper = require('casper').create verbose: true
2
3 countLinks = -> document.querySelectorAll('a').length
4
5 suites = [
6 ->
7 @echo 'Suite 1'
8 @start 'http://google.com/', -> @echo "Page title: #{@getTitle()}"
9 @then -> @echo "#{@evaluate(countLinks)} links"
10 ->
11 @echo 'Suite 2'
12 @start 'http://yahoo.com/', -> @echo "Page title: #{@getTitle()}"
13 @then -> @echo "#{@evaluate(countLinks)} links"
14 ->
15 @echo 'Suite 3'
16 @start 'http://bing.com/', -> @echo "Page title: #{@getTitle()}"
17 @then -> @echo "#{@evaluate(countLinks)} links"
18 ]
19
20 casper.start()
21
22 casper.then -> @echo('Starting')
23
24 currentSuite = 0;
25
26 check = ->
27 if suites[currentSuite]
28 suites[currentSuite].call @
29 currentSuite++;
30 casper.run check
31 else
32 @echo 'All done.'
33 @exit()
34
35 casper.run check
1 ### This script will capture a screenshot of a twitter account page
2
3 Usage $ casperjs screenshot.coffee <twitter-account>
4 ###
5 casper = require('casper').create
6 viewportSize:
7 width: 1024
8 height: 768
9
10 twitterAccount = casper.cli.get(0)
11 filename = casper.cli.get(1)
12
13 if not twitterAccount or not filename or not /\.(png|jpg|pdf)$/i.test(filename)
14 casper.echo "Usage $ casperjs samples/screenshot.coffee <twitter-account> <filename.[jpg|png|pdf]>"
15 casper.exit()
16
17 casper.start "https://twitter.com/#!/#{twitterAccount}", ->
18 capture = ->
19 @captureSelector filename, 'html'
20 @echo "Saved screenshot of #{@getCurrentUrl()} to #{filename}"
21 @waitForSelector '.tweet-row', capture, null, 12000
22
23 casper.run()
1 /** 1 /**
2 * This script will capture a screenshot of a twitter account page 2 * This script will capture a screenshot of a twitter account page
3 * 3 *
4 * Usage $ casperjs screenshot.coffee <twitter-account>
4 */ 5 */
5 var casper = require('casper').create({ 6 var casper = require('casper').create({
6 logLevel: "debug",
7 verbose: true,
8 viewportSize: { 7 viewportSize: {
9 width: 1024, 8 width: 1024,
10 height: 768 9 height: 768
11 } 10 }
12 }); 11 });
13 12
14 casper.start('https://twitter.com/#!/twilio', function(self) { 13 var twitterAccount = casper.cli.get(0);
15 self.waitForSelector('.tweet-row', function(self) { 14 var filename = casper.cli.get(1);
16 self.captureSelector('twitter.png', 'html'); 15
17 }, null, 12000); 16 if (!twitterAccount || !filename || !/\.(png|jpg|pdf)$/i.test(filename)) {
17 casper.echo("Usage $ casperjs samples/screenshot.coffee <twitter-account> <filename.[jpg|png|pdf]>");
18 casper.exit();
19 }
20
21 casper.start('https://twitter.com/#!/' + twitterAccount, function() {
22 this.waitForSelector('.tweet-row', function() {
23 this.captureSelector(filename, 'html');
24 this.echo("Saved screenshot of " + this.getCurrentUrl() + " to " + filename);
25 }, function() {
26 this.die('Timeout reached. Fail whale?').exit();
27 }, 12000);
18 }); 28 });
19 29
20 casper.run(); 30 casper.run();
......
1 ###
2 This script will add a custom HTTP status code handler, here for 404 pages.
3 ###
4 casper = require('casper').create
5 httpStatusHandlers:
6 404: (self, resource) ->
7 @echo "Resource at #{resource.url} not found (404)", "COMMENT"
8
9 casper.start 'http://www.google.com/plop', ->
10 @echo 'Done.'
11 @exit()
12
13 casper.run()
1 failed = [];
2
3 casper = require('casper').create
4 onStepTimeout: -> failed.push @requestUrl
5
6 links = [
7 'http://google.com/'
8 'http://akei.com/'
9 'http://lemonde.fr/'
10 'http://liberation.fr/'
11 'http://cdiscount.fr/'
12 ]
13
14 timeout = ~~casper.cli.get(0)
15 timeout = 1000 if timeout < 1
16 casper.options.stepTimeout = timeout
17
18 casper.echo "Testing with timeout=#{casper.options.stepTimeout}ms."
19
20 casper.start()
21
22 casper.each links, (self, link) ->
23 @test.comment "Adding #{link} to test suite"
24 @thenOpen link, ->
25 if @requestUrl in failed
26 @test.fail "#{@requestUrl} loaded in less than #{timeout}ms."
27 else
28 @test.pass "#{@requestUrl} loaded in less than #{timeout}ms."
29
30 casper.run -> @test.renderResults true
1 ###
2 Just a silly game.
3
4 $ casperjs samples/timeout.js 500
5 Will google.com load in less than 500ms?
6 NOPE.
7 $ casperjs samples/timeout.js 1000
8 Will google.com load in less than 1000ms?
9 NOPE.
10 $ casperjs samples/timeout.js 1500
11 Will google.com load in less than 1500ms?
12 NOPE.
13 $ casperjs samples/timeout.js 2000
14 Will google.com load in less than 2000ms?
15 YES!
16 ###
17 casper = require('casper').create
18 onTimeout: ->
19 @echo 'NOPE.', 'RED_BAR'
20 @exit()
21
22 timeout = ~~casper.cli.get(0);
23 if timeout < 1
24 casper.echo "You must pass a valid timeout value"
25 casper.exit()
26
27 casper.echo "Will google.com load in less than #{timeout}ms?"
28 casper.options.timeout = timeout;
29
30 casper.start 'http://www.google.com/', ->
31 @echo 'YES!', 'GREEN_BAR'
32 @exit()
33
34 casper.run()
...\ No newline at end of file ...\ No newline at end of file