-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseNespresso.ts
67 lines (56 loc) · 2 KB
/
parseNespresso.ts
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
import axios from "axios";
import {get} from 'lodash';
import {HTMLElement, parse} from "node-html-parser";
function getPrice(element: HTMLElement) {
const priceNode = element.querySelector('[itemprop=price]');
const groupPriceNode = element.querySelector('.price');
let price = '';
if (priceNode) {
price = priceNode.attributes.content;
} else if (groupPriceNode) {
price = groupPriceNode.text;
}
return price;
}
class NespressoItem {
constructor(
public name: string,
public description: string,
public price: string,
public img?: string,
public intensity?: string,
public group?: string,
) {
}
static fromHtmlNode(element: HTMLElement, group?: string) {
const nameNode = element.querySelector('[itemprop=name]');
const photoNode = element.querySelector('.photo.image');
const descriptionNode = element.querySelector('[itemprop=description]');
const countNode = element.querySelector('.tooltip.count')
return new NespressoItem(
get(nameNode, 'text', ''),
get(descriptionNode, 'text', ''),
getPrice(element),
get(photoNode, 'attributes.src', ''),
get(countNode, 'text', ''),
group
);
}
}
export async function parseNespresso() {
const {data} = await axios.get('https://www.nespresso.com/ru/ru/coffee-capsules/original');
const root = parse(data);
if (!root.valid || !(root instanceof HTMLElement)) {
return;
}
const list = root.querySelector('ol.products.list.items.product-items').querySelectorAll('li');
let group = '';
return list.reduce((acc, item) => {
if (item.classNames.includes('product-item-meta')) {
group = item.querySelector('.product-item-title').text;
return acc;
}
const nespressoItem = NespressoItem.fromHtmlNode(item, group);
return [...acc, nespressoItem];
}, [] as NespressoItem[]);
}