-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.js
285 lines (224 loc) · 7.16 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
const util = require('util');
const { chromium } = require('playwright');
const cheerio = require('cheerio');
const delay = util.promisify(setTimeout);
const SEARCH = '/search';
const DEFAULT_OPTIONS = {
num: 10,
retry: 5,
delay: 0,
headless: true,
// request can be slow if a scrape API is used.
timeout: 60000
};
/**
* Make a search based on a keyword on a google domain
*
* @param {json} params the options used to make the google search, based on the following structure :
* {
* host : "google.be", //the google host (eg : google.com, google.fr, ... - default : google.com)
* num : 100, // number of result
* qs : {
* q : "keyword", // The keyword
* hl : "fr" // the language (iso code), if not specify, the SERP can contains a mix
* //and all query parameters supported by Google : https://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters
* }
* }
* @returns {Array<string>} list of url that match to the Google SERP
*/
async function search(params) {
const options = await buildOptions(params);
try {
const result = await doRequest(options);
if (Array.isArray(result)) {
return result.slice(0, options.num);
}
return result;
} finally {
await options.browser.close();
}
}
/**
* Check is the search options are well defined & add default value
*
* @param {Json} params The params to check
* @returns {Json} a Json clone of the params with default values
*/
async function buildOptions(params) {
if (!params.qs) {
throw new Error('No qs attribute in the options');
}
if (!params.qs.q) {
throw new Error('the option object doesn\'t contain the keyword');
}
const options = Object.assign({}, DEFAULT_OPTIONS, params);
if (options.numberOfResults) {
options.qs.hl = 'EN';
}
options.browser = await chromium.launch({ headless: options.headless });
return options;
}
/**
* Execute a Google request with some retries in the case of errors
*
* @param {Json} options The search options
* @param {number} nbrOfLinks the number of links already retrieved
* @returns {Array<string>|number} The list of url found in the SERP or the number of result
*/
async function doRequest(options, nbrOfLinks = 0) {
let response = -1;
for (let i = 0; i < options.retry; i += 1) {
try {
/* eslint-disable no-await-in-loop */
await delay(options.delay);
response = await execRequest(options, nbrOfLinks);
break;
} catch (error) {
if (i === options.retry - 1) {
throw error;
}
}
}
return response;
}
/**
* Execute a Google Request with the help of playwright in order to accept the cookie consent
*
* @param {Json} options The search options
* @param {number} nbrOfLinks the number of links already retrieved
* @returns {Array<string>|number} The list of url found in the SERP or the number of result
*/
async function execRequest(options, nbrOfLinks) {
const content = await requestFromBrowser(buildUrl(options), options);
if (options.numberOfResults) {
return getNumberOfResults(content);
}
return await getLinks(options, content, nbrOfLinks);
}
async function requestFromBrowser(url, options) {
const page = await newPage(options);
const response = await page.goto(url);
if (response && !response.ok()) {
throw new Error(`Invalid HTTP status code on ${ options.url }`);
}
// If the cookie consent button exist on the page, click on it
const consentButton = await page.$('//div[text()=\'I agree\']');
if (consentButton) {
await consentButton.click();
}
return await page.content();
}
async function newPage(options) {
const contextOptions = {};
if (options.proxy) {
contextOptions.proxy = options.proxy;
}
if (options.proxyList) {
contextOptions.proxy = pickNewProxy(options);
}
const context = await options.browser.newContext(contextOptions);
const page = await context.newPage();
return page;
}
function pickNewProxy(options) {
if (!options.proxyList) {
throw new Error('There is no proxy list in the options');
}
const p = options.proxyList.pick();
return {
server: `http://${ p.host }:${ p.port }`,
username: p.userName,
password: p.password
};
}
/**
* Return the number of result found in Google
*
* @param {Object} content The Http body content
* @returns {number} The number of results
*/
function getNumberOfResults(content) {
const $ = cheerio.load(content);
const hasNumberofResult = $('body').find('#result-stats').length > 0;
if (!hasNumberofResult) {
return 0;
}
const result = $('#result-stats').text().split(' ');
if (result.length > 1) {
// Convert String with a format number into a number
return Number(result[1].replace(/\D/g, ''));
}
return 0;
}
/**
* Get all URL(links) found in the top positions of the SERP
*
* @param {Json} options The search options
* @param {Object} content The html content
* @param {number} nbrOfLinks the number of links already retrieved
* @returns {Array} The list of the links
*/
async function getLinks(options, content, nbrOfLinks) {
const result = extractLinks(content);
let allLinks = result.links;
if (allLinks.length === 0) {
return allLinks;
}
const nbr = nbrOfLinks + allLinks.length;
if (nbr >= options.num) {
return allLinks;
}
if (result.nextPage) {
const nextPageOptions = Object.assign({}, options);
nextPageOptions.path = result.nextPage;
allLinks = [ ...allLinks, ...await doRequest(nextPageOptions, nbr) ];
}
return allLinks;
}
/**
* Build the url used to make the request on Google. It could be done directly or via a scrape api url
*
* @param {json} options the options used to build the url
* @returns {string} the url
*/
function buildUrl(options) {
return options.scrapeApiUrl ? `${ options.scrapeApiUrl }&url=${ buildGoogleUrl(options) }` : buildGoogleUrl(options);
}
function buildGoogleUrl(options) {
// path is used when we request the second page of the SERP
if (options.path) {
return `https://www.${ options.host || 'google.com' }${ options.path }`;
}
const url = `https://www.${ options.host || 'google.com' }${ SEARCH }`;
const queryparams = [];
// eslint-disable-next-line guard-for-in
for (const q in options.qs) {
queryparams.push(`${ q }=${ options.qs[q] }`);
}
return encodeURI(`${ url }?${ queryparams.join('&') }`);
}
/**
* extractLinks - Get the links from the HTML body
*
* @param {type} body th HTML body
* @returns {Object} The list of the links & information about the next SERP page
*/
function extractLinks(body) {
const links = [];
const $ = cheerio.load(body);
// Get the links matching to the web sites
// Update May 2020 : search only the h3. Google changes its CSS name
// $('body').find('.srg h3').each((i, h3) => {
$('body').find('h3').each((i, h3) => {
if ($(h3).parent()) {
const href = $(h3).parent().attr('href');
if (href) {
links.push({ url: href, title: $(h3).text() });
}
}
});
// Get the link used to access to the next google page for this result
const nextPage = $('#pnnext').attr('href');
return { links, nextPage };
}
module.exports.search = search;