-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.js
84 lines (74 loc) · 2.3 KB
/
fetch.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
const { Chromeless } = require("chromeless");
const { JSDOM } = require("jsdom");
const axios = require("axios");
const shopData = require("./shopData");
require("dotenv").config();
async function runBrowser(shop) {
const chromeless = new Chromeless();
let value;
try {
value = await chromeless
.setUserAgent(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
)
.goto(shop.url, 20000)
.evaluate(async (shop) => {
if (document.querySelector(shop.selector)) {
return document.querySelector(shop.selector).innerText;
} else {
throw new Error("Feil med selector");
}
}, shop)
.end();
} catch (error) {
console.log(error);
}
return { name: shop.name, statusChanged: value !== shop.value, value };
}
async function runAxios(shop) {
let value;
try {
const response = await axios.get(shop.url);
const dom = new JSDOM(response.data);
if (dom.window.document.querySelector(shop.selector)) {
value = dom.window.document
.querySelector(shop.selector)
.textContent.replace(/[\n\r]+|[\s]{2,}/g, "");
} else {
throw new Error("Feil med selector hos ", shop.name);
}
} catch (error) {
console.log(error);
}
return { name: shop.name, statusChanged: value !== shop.value, value };
}
let results = [];
const loop = async () => {
for (let i = 0; i < shopData.length; i++) {
const shop = shopData[i];
console.log("Starter", shop.name);
let res;
if (shop.browser) {
res = await runBrowser(shop);
} else {
res = await runAxios(shop);
}
results.push(res);
}
};
const run = async () => {
console.log("----------- STARTER SCRAPING -----------");
await loop();
console.log("RESULTATER: ", results);
const changedShops = results.filter((shop) => shop.statusChanged);
if (changedShops.length > 0) {
const shopNames = changedShops.map((shop) => shop.name).join(", ");
console.log("Changed Shops", shopNames);
console.log("SENDER VARSEL");
axios.post(`https://maker.ifttt.com/trigger/${process.env.IFTTT_EVENT}/with/key/${process.env.IFTTT_NOTIFICATION_KEY}`, {
value1: shopNames,
});
}
console.log("----------- SCRAPING OVER -----------");
};
run();