added new sample: googlematch.js
Showing
1 changed file
with
62 additions
and
0 deletions
samples/googlematch.js
0 → 100644
1 | /** | ||
2 | * Takes provided terms passed as arguments and query google for the number of | ||
3 | * estimated results each have. | ||
4 | * | ||
5 | * Usage: | ||
6 | * $ phantomjs samples/googlematch.js nicolas chuck borris | ||
7 | * nicolas: 69600000 | ||
8 | * chuck: 49500000 | ||
9 | * borris: 2370000 | ||
10 | * winner is "nicolas" with 69600000 results | ||
11 | */ | ||
12 | phantom.injectJs('casper.js'); | ||
13 | |||
14 | phantom.Casper.extend({ | ||
15 | fetchScore: function() { | ||
16 | return this.evaluate(function() { | ||
17 | var result = document.querySelector('#resultStats').innerText; | ||
18 | return Number(/Environ ([0-9\s]{1,}).*/.exec(result)[1].replace(/\s/g, '')); | ||
19 | }); | ||
20 | } | ||
21 | }); | ||
22 | |||
23 | var casper = new phantom.Casper({ | ||
24 | verbose: true | ||
25 | }), terms = phantom.args, scores = [], i = 0; | ||
26 | |||
27 | if (terms.length < 2) { | ||
28 | casper.log('usage: phantomjs googlematch.js term1, term2 [, term3]...').exit(); | ||
29 | } | ||
30 | |||
31 | casper.start("http://google.fr/"); | ||
32 | |||
33 | casper.repeat(terms.length, function(self) { | ||
34 | self.then((function(casper, i) { | ||
35 | return function(self) { | ||
36 | self.fill('form[name=f]', { | ||
37 | q: terms[i] | ||
38 | }, true); | ||
39 | }; | ||
40 | })(self, i)); | ||
41 | self.then((function(casper, i) { | ||
42 | return function(self) { | ||
43 | var term = terms[i], score = self.fetchScore(); | ||
44 | scores.push({ | ||
45 | term: term, | ||
46 | score: score | ||
47 | }); | ||
48 | self.echo(term + ': ' + score); | ||
49 | }; | ||
50 | })(self, i)); | ||
51 | i++; | ||
52 | }); | ||
53 | |||
54 | casper.run(function(self) { | ||
55 | scores.sort(function(a, b) { | ||
56 | return a.score - b.score; | ||
57 | }); | ||
58 | var winner = scores[scores.length - 1]; | ||
59 | self.echo('winner is "' + winner.term + '" with ' + winner.score + ' results') | ||
60 | self.exit(); | ||
61 | }); | ||
62 |
-
Please register or sign in to post a comment