-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listing-4.2.js
51 lines (46 loc) · 1.48 KB
/
listing-4.2.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
"use strict";
const request = require('request-promise');
const cheerio = require('cheerio');
function scrapeWebPage (url) {
return request.get(url)
.then(response => {
const $ = cheerio.load(response);
const headers = $("thead tr")
.map((i, el) => {
return $(el)
.find("th")
.map((i, el) => {
return $(el).text();
})
.toArray();
})
.toArray();
const rows = $("tbody tr")
.map((i, el) => {
return [$(el)
.find("td")
.map((i, el) => {
return $(el).text();
})
.toArray()];
})
.toArray();
return rows.map(row => {
const record = {};
headers.forEach((fieldName, columnIndex) => {
if (fieldName.trim().length > 0) {
record[fieldName] = row[columnIndex];
}
});
return record;
});
});
};
const url = "https://earthquake.usgs.gov/earthquakes/browse/largest-world.php";
scrapeWebPage(url)
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});