-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpageScraper.js
72 lines (63 loc) · 1.85 KB
/
pageScraper.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
const fs = require("fs");
const { sendNotification } = require("./mailer");
const scraperObject = {
baseUrl: "https://jp.mercari.com/search?keyword=",
async scraper(browser, data) {
const keyword = data.keyword;
const max = data.maxPrice;
const min = data.minPrice;
const to = data.emailTo;
let page = await browser.newPage();
const targetUrl = this.baseUrl + keyword;
console.log(`Navigating to ${targetUrl}...`);
await page.goto(targetUrl);
await page.waitForSelector("#item-grid");
const info = await page.$$eval("mer-item-thumbnail", (items) => {
const info = items.map((el) => {
return {
price: el.getAttribute("price"),
name: el.getAttribute("alt"),
};
});
return info;
});
const latestItems = info.filter(
(item) =>
min < item.price && item.price < max && item.name.includes(keyword)
);
const json = JSON.stringify(latestItems);
let oldItems = [];
try {
oldItems = JSON.parse(fs.readFileSync(`last${keyword}.json`, "utf-8"));
} catch (e) {
console.error(e);
}
fs.writeFile(`last${keyword}.json`, json, "utf-8", (err) => {
console.error(err);
});
const newItems = findUpdatedOrNewItems(latestItems, oldItems);
if (!!newItems.length) {
await sendNotification(
to,
`new ${keyword} was found with ${newItems[0].price} yen`,
`link: ${targetUrl}`
);
}
console.log("newItems", newItems);
return newItems;
},
};
function findUpdatedOrNewItems(latestItems, oldItems) {
const newItems = [];
latestItems.forEach((item) => {
if (
oldItems.filter(
(oldItem) => oldItem.price === item.price && oldItem.name === item.name
).length === 0
) {
newItems.push(item);
}
});
return newItems;
}
module.exports = scraperObject;