-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
170 lines (150 loc) · 5.11 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
require('dotenv').load();
const axios = require('axios');
const cheerio = require('cheerio');
const storage = require('@google-cloud/storage')();
const CACHE_LINK = 'https://webcache.googleusercontent.com/search?q=cache:kK5T6Z39UOIJ:gothamist.com/+&cd=20&hl=en&ct=clnk&gl=us';
const bucket = storage.bucket('amp-archive');
const wait = (milliseconds) => {
return new Promise((resolve, reject) => setTimeout(resolve, milliseconds));
}
const getAmpUrls = (originalUrls) => {
console.log('getting amped');
return axios.post(`https://acceleratedmobilepageurl.googleapis.com/v1/ampUrls:batchGet?key=${process.env.GOOGLE_API_KEY}`,
{
'urls': originalUrls,
'lookupStrategy': 'IN_INDEX_DOC'
}).then((response) => {
const cacheUrls = response.data.ampUrls.map((meta) =>
meta.ampUrl
.replace('http://', 'https://www.google.com/amp/')
.replace('?', '%3f'));
return cacheUrls;
}).catch((error) => {
console.error('error', error.response.data);
});
};
const authorPageURLs = (name) => {
return [
`gothamist.com/author/${encodeURIComponent(name)}`,
`laist.com/author/${encodeURIComponent(name)}`,
`dcist.com/author/${encodeURIComponent(name)}`,
`chicagoist.com/author/${encodeURIComponent(name)}`,
`sfist.com/author/${encodeURIComponent(name)}`,
`shanghaiist.com/author/${encodeURIComponent(name)}`,
];
}
const recurseAmpScrape = (urls) => {
if (!urls.length) return Promise.resolve();
const batch = urls.shift();
// Googles rate limits are really strict
return getAmpUrls(batch)
.then((cacheUrls) => {
const scrapePromises = cacheUrls.map((url) => storeArticle(url).catch(err => {
if (err.message !== 'nosrc') throw err;
}));
return Promise.all(scrapePromises);
})
.then(() => wait(15000))
.then(() => recurseAmpScrape(urls));
}
const scrapeAuthor = (name) => {
// Search google for cache link
//do something here
const queryURLs = authorPageURLs(name);
const promises = queryURLs.map((queryURL) => {
return axios.get(`https://www.google.com/search?q=${encodeURIComponent(queryURL)}`)
.then((resp) => {
const $ = cheerio.load(resp.data);
console.log('getting cache');
const cacheUrl = $('a._Zkb').attr('href');
if (!cacheUrl) throw 'nocacheurl';
console.log('found at', queryURL);
return axios.get(`http://google.com${cacheUrl}`);
})
.then((resp) => {
const $ = cheerio.load(resp.data);
const articleLinks = $('.main-item-summary-content a');
const articleUrls = [];
articleLinks.each((i, linkEl) => {
const link = $(linkEl);
const articleTitle = link.text();
const articleURL = link.attr('href');
articleUrls.push(articleURL);
});
return articleUrls;
})
.then((articleUrls) => {
const splitUrls = [];
while(articleUrls.length > 0) {
splitUrls.push(articleUrls.splice(0, 50));
}
return recurseAmpScrape(splitUrls);
})
.catch(err => {
console.log('nocacheurl', name);
if (err === 'nocacheurl') return;
throw err;
})
.catch(err => {
// If its an axios error, not all is lost
if (err.response) {
console.error(err.response);
return;
}
throw err;
});
});
return Promise.all(promises);
}
const storeArticle = (url) => {
if (!url) return Promise.reject(new Error('nosrc'));
return axios({
method:'get',
url: url,
headers: {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1'}
})
.then((response) => {
const $ = cheerio.load(response.data);
const iframeSrc = $('iframe').attr('src');
if (!iframeSrc) throw new Error('nosrc');
return axios({
method:'get',
url: iframeSrc,
headers: {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1'}
});
})
.then((response) => {
const $ = cheerio.load(response.data);
const title = $('h1').text();
const authorSubtitlePieces = $('h1').next('p').text().split(' ');
// Do a little dance to get the author
let i;
const authorPieces = [];
for (i = 0; i < authorSubtitlePieces.length; i++) {
const piece = authorSubtitlePieces[i];
if (piece === 'by') continue;
if (piece === 'in') break;
authorPieces.push(piece);
}
const authorName = authorPieces.join(' ');
const deslashedTitle = title.replace('/', '-');
const filename = `${authorName}/${deslashedTitle}.html`;
console.log('aboutta save');
return bucket.file(filename).save(
response.data,
{
metadata: {
contentType: 'text/html',
}
});
})
.catch(err => {
// If its an axios error, not all is lost
if (err.response) {
console.log('axios error', err.response.status);
return;
}
throw err;
});;
}
scrapeAuthor('Emma Specter').then(() => process.exit(0));