-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
260 lines (213 loc) · 7.04 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
const util = require('util')
const request = require('request-promise-native')
const cheerio = require('cheerio')
const delay = util.promisify(setTimeout)
const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
const DEFAULT_OPTIONS = {
num: 10,
retry: 3,
delay: 0,
resolveWithFullResponse: true,
jar: true
}
/**
* 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
* }
* // If needed, add all request options like proxy : https://github.com/request/request
* }
* @returns {Array<string>} list of url that match to the Google SERP
*/
async function search (params) {
const options = check(params)
const result = await doRequest(options, 0)
if (Array.isArray(result)) {
return result.slice(0, options.num)
}
return result
}
/**
* check - Check is the search options are well defined & add default value
*
* @param {Json} params The options to check
* @returns {Json} a Json clone of the params with default values
*/
function check (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)
options.url = getGoogleUrl(options, '/search')
// Making request on Google without user agent => not a good idea
const hasUserAgent = (options.headers || {})['User-Agent']
if (!hasUserAgent) {
options.headers = options.headers || {}
options.headers['User-Agent'] = DEFAULT_USER_AGENT
}
if (options.proxyList) {
options.proxy = options.proxyList.pick().getUrl()
}
return options
}
/**
* tryRequest - 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) {
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) {
logError(`Error during the request, retry : ${i}`, options, error)
if (options.proxyList) {
/* eslint-disable no-param-reassign */
options.proxy = options.proxyList.pick().getUrl()
}
if (i === options.retry - 1) {
throw error
}
}
}
return response
}
/**
* execRequest - Execute a Google Request
*
* @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) {
// If we want to get the number of results => force the interface language = EN
// Otherwise it becomes difficult to parse the html body
if (options.numberOfResults) {
options.qs.hl = 'EN'
}
const response = await request(options)
if (response && response.statusCode !== 200) {
throw new Error(`Invalid HTTP status code on ${options.url}`)
}
if (options.numberOfResults) {
return getNumberOfResults(options, response)
}
return await getLinks(options, response, nbrOfLinks)
}
/**
* getNumberOfResults - Return the number of result found in Google
*
* @param {Json} options The search options
* @param {Object} response The Http response
* @returns {number} The number of results
*/
function getNumberOfResults (options, response) {
const $ = cheerio.load(response.body)
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
}
/**
* getLinks - Get all URL(links) found in the top positions of the SERP
*
* @param {Json} options The search options
* @param {Object} response The Http response
* @param {number} nbrOfLinks the number of links already retrieved
* @returns {Array} The list of the links
*/
async function getLinks (options, response, nbrOfLinks) {
const result = extractLinks(options, response.body)
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.url = getGoogleUrl(options, result.nextPage)
allLinks = [...allLinks, ...await doRequest(nextPageOptions, nbr)]
}
return allLinks
}
/**
* extractLinks - Get the links from the HTML body
*
* @param {Json} options The search options
* @param {type} body th HTML body
* @returns {Object} The list of the links & information about the next SERP page
*/
function extractLinks (options, 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) {
const ignore = options.ignore || []
const l = ignore.length
if (l > 0) {
let flag = 0
for (let i = 0; i < l && flag === 0; i++) {
if (href.includes(ignore[i])) flag = 1
}
if (flag === 0) links.push({ url: href, title: $(h3).text() })
} else {
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 }
}
/**
* getGoogleUrl - description
*
* @param {type} options description
* @param {type} path description
* @returns {type} description
*/
function getGoogleUrl (options, path) {
return `https://www.${options.host || 'google.com'}${path}`
}
/**
* logError - description
*
* @param {type} message description
* @param {type} options description
* @param {type} error description
*/
function logError (message, options, error) {
console.error({ module: 'serp', message, url: options.url, proxy: options.proxy, error, options })
}
module.exports.search = search