Commit 329b0b7e 329b0b7e89fac11701becaaef5bda79e3af1e37d by Nicolas Perriault

ported all samples to coffeescript

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