-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
65 lines (54 loc) · 1.6 KB
/
index.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
const fs = require('fs');
const Nightmare = require('nightmare');
const nm = Nightmare({show: true});
const baseUrl = 'http://www.nhm.ac.uk';
let acc = [];
nm.goto(`${baseUrl}/discover/dino-directory/name/name-az-all.html`)
.evaluate(function() {
let results = [];
let dinoLinks = document.querySelectorAll('.dino-list a');
for(let i=0; i < dinoLinks.length; i++) {
results.push(dinoLinks[i].getAttribute('href'));
}
return results;
}).then(crawl).catch(bail);
function crawl(urls) {
if (urls.length < 2) {
nm.goto(baseUrl + urls.pop())
.evaluate(scrape, acc)
.end()
.then(function(result) {
acc = result;
let dinos = { dinosaurs: acc };
fs.writeFileSync('results/dinos.json', JSON.stringify(dinos), 'utf8');
console.log(`Finished scraping ${acc.length} dinos to results/dinos.json`);
})
.catch(bail);
} else {
nm.goto(baseUrl + urls.pop())
.evaluate(scrape, acc)
.then(function(result) {
acc = result;
crawl(urls);
})
.catch(bail);
}
}
function scrape(acc) {
let result = {};
let keys = document.querySelectorAll('.dino-facts dt');
let values = document.querySelectorAll('.dino-facts dd');
for (let i=0; i<keys.length; i++) {
let words = keys[i].innerText.trim().split(' ')
let key = words.map(function(w, i) {
return w.toLowerCase();
}).join('_');
result[key] = values[i].innerText.trim();
}
result['name'] = document.querySelector('#dino-intro h2').innerText;
acc.push(result);
return acc;
}
function bail(err) {
console.error(err);
}