-
Notifications
You must be signed in to change notification settings - Fork 17
/
WikiPhilosophy.js
76 lines (64 loc) · 1.58 KB
/
WikiPhilosophy.js
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
/*
* Getting to Philosophy
* https://en.wikipedia.org/wiki/Wikipedia:Getting_to_Philosophy
*/
"use strict";
var webdriver = require('selenium-webdriver');
var browser = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();
var counter = 0;
function strip(str) {
var d = 0, k = 0;
var c;
var out = '';
for (var i=0; i<str.length; i++) {
c = str[i];
if (d < 1) {
if (c === '>') {
k -= 1;
}
if (c === '<') {
k += 1;
}
}
if (k < 1) {
if (c === '(') {
d +=1;
}
if (d > 0) {
out += ' ';
} else {
out += c
}
if (c === ')') {
d -= 1;
}
} else {
out += c;
}
}
return out.replace(/'/g, '').trim();
}
function clean(str) {
var promise = webdriver.promise.defer();
var para = browser.findElement(webdriver.By.css('#mw-content-text > p'));
para.getInnerHtml().then(function(html){
html = strip(html);
var script = "document.querySelector('#mw-content-text > p').innerHTML = '" + html + "'";
browser.executeScript(script).then(promise.fulfill);
});
return promise.promise;
}
function findLink() {
browser.findElement(webdriver.By.css('#mw-content-text > p a[title]')).then(function(link) {
link.getAttribute('title').then(function(text) {
console.log(++counter + '. ' + text);
if (text === 'Philosophy') {
console.log('\nReached Philosophy in '+ counter +' hops.\n');
browser.quit();
} else {
link.click().then(clean).then(findLink);
}
})
})
}
browser.get('http://en.wikipedia.org/wiki/Special:Random').then(clean).then(findLink);