-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
59 lines (48 loc) · 1.33 KB
/
browser.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
const puppeteer = require('puppeteer');
const config = require('./config.js');
Object.assign(exports, {
async execute(job) {
const browser = await puppeteer.launch({ args: config.puppeteer_args });
const page = await browser.newPage();
let result = null;
let error = null;
try {
await page.goto(job.url, {
timeout: 15 * 1000,
waitUntil: 'networkidle2'
});
result = await page.evaluate((query) => {
let search = '';
if (query.mode === 'query') {
const el = document.querySelector(query.selector);
search = el ? el.textContent.trim() : '';
} else if (query.mode === 'regex') {
const match = document.body.textContent.match(
new RegExp(query.selector)
);
search = match ? match[0].trim() : '';
}
const number = Number(search);
if (search.length && !isNaN(number)) {
search = number;
}
return search;
}, job.query);
} catch (e) {
error = e;
}
await browser.close();
if (error) {
return Promise.reject({
time: new Date(),
value: error.message,
kind: 'error'
});
}
return {
time: new Date(),
value: result,
kind: typeof result === 'string' ? 'text' : 'number'
};
}
});