-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscraper.js
88 lines (76 loc) · 1.99 KB
/
scraper.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
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const validParams = [
'auth_password',
'auth_username',
'cookie',
'country',
'referer',
'selector',
]
function scraper(url, params, headers={}, timeout=5000){
try {
let vURL = new URL(url)
} catch(e) {
throw new Error(e.message)
}
let apiKey = process.env.PROMPTAPI_TOKEN
if (!apiKey) {
throw new Error('You need to set PROMPTAPI_TOKEN environment variable')
}
let needParams = {url: url}
Object.keys(params).forEach(paramName => {
if (validParams.indexOf(paramName) > -1){
needParams[paramName] = params[paramName]
}
})
let promptAPIEndPoint = 'https://api.promptapi.com/scraper'
let defaultHeaders = {
'apikey': apiKey
}
if(Object.keys(headers).length > 0 && headers.constructor === Object){
Object.assign(defaultHeaders, headers)
}
let config = {
method: 'get',
url: promptAPIEndPoint,
params: needParams,
headers: defaultHeaders,
timeout: timeout,
};
return axios(config).then(response => {
if (response.data['data-selector']){
response.data.data = response.data['data-selector']
}
return response.data
})
.catch(error => {
if (error.response) {
return {error: error.response.data.message}
} else {
return {error: error.message}
}
});
}
function save(filename, data){
let fileDirname = path.dirname(filename)
let fileExt = path.extname(filename)
let fileBasename = path.basename(filename, fileExt)
let targetExt = '.html'
saveData = data
if (typeof(data) === 'object'){
targetExt = '.json'
saveData = JSON.stringify(data)
}
fileSavename = `${fileDirname}/${fileBasename}${targetExt}`
fs.writeFile(fileSavename, saveData, (err) => {
if (err) throw err;
let stats = fs.statSync(fileSavename)
console.log(`${fileSavename} saved successfully, written ${stats["size"]} bytes`);
});
}
module.exports = {
scraper,
save,
}