File size: 7,807 Bytes
4a51346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import puppeteer from 'puppeteer';
import minimist from 'minimist';
import fs from 'fs-extra';

const run = async (
	name,
	countryCode = 'US',
	stateCode = '',
	minPrice,
	maxPrice,
	noPriceIncluded,
	minRatings,
	maxRatings,
	minAverage,
	maxAverage,
) => {
	// set country and state
	const setShipTo = async (countryCode, stateCode) => {
		return await page.evaluate(
			async (countryCode, stateCode) => {
				const fetchResult = await fetch('https://www.vivino.com/api/ship_to/', {
					headers: {
						'content-type': 'application/json',
						'x-csrf-token': document.querySelector('[name="csrf-token"]').content,
					},
					body: JSON.stringify({
						country_code: countryCode,
						state_code: stateCode,
					}),
					method: 'PUT',
				});
				if (fetchResult.status === 200) {
					const result = await fetchResult.json();
					if (
						result.ship_to.country_code.toLowerCase() === countryCode.toLowerCase() &&
						result.ship_to.state_code.toLowerCase() === stateCode.toLowerCase()
					) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			},
			countryCode,
			stateCode,
		);
	};

	// check country and state
	const isShipTo = async (countryCode, stateCode) => {
		return await page.evaluate(
			(countryCode, stateCode) => {
				if (
					countryCode.toLowerCase() === window.__PRELOADED_COUNTRY_CODE__.toLowerCase() &&
					stateCode.toLowerCase() === window.__PRELOADED_STATE_CODE__.toLowerCase()
				) {
					return true;
				}
				return false;
			},
			countryCode,
			stateCode,
		);
	};

	// collect items from the page
	const collectItems = () => {
		const numerize = (stringNumber) => {
			const str = stringNumber.replace(/[^0-9,.]+/g, '').replace(',', '.');
			return parseFloat(str);
		};

		const CARDS_SELECTOR = '.card.card-lg';
		const NAME_SELECTOR = '.wine-card__name';
		const COUNTRY_SELECTOR = '.wine-card__region [data-item-type="country"]';
		const REGION_SELECTOR = '.wine-card__region .link-color-alt-grey';
		const AVERAGE_RATING_SELECTOR = '.average__number';
		const RATINGS_SELECTOR = '.average__stars .text-micro';
		const RATING_REPLACMENT = 'ratings';
		const LINK_SELECTOR = 'a';
		const THUMB_SELECTOR = 'figure';
		const THUMB_REGEX = /"(.*)"/;
		const PRICE_SELECTOR = '.wine-price-value';

		const data = [...document.querySelectorAll(CARDS_SELECTOR)].map((e) => {
			const name = e.querySelector(NAME_SELECTOR).textContent.trim();
			const link = e.querySelector(LINK_SELECTOR).href;
			const thumb = e.querySelector(THUMB_SELECTOR)
				? 'https:' + e.querySelector(THUMB_SELECTOR).style.backgroundImage.match(THUMB_REGEX)[1]
				: undefined;
			const country = e.querySelector(COUNTRY_SELECTOR).textContent.trim();
			const region = e.querySelector(REGION_SELECTOR).textContent.trim();
			const average_rating = e.querySelector(AVERAGE_RATING_SELECTOR)
				? numerize(e.querySelector(AVERAGE_RATING_SELECTOR).textContent.trim())
				: undefined;
			const ratings = e.querySelector(RATINGS_SELECTOR)
				? Number(
					e.querySelector(RATINGS_SELECTOR).textContent.replace(RATING_REPLACMENT, '').trim(),
				  )
				: undefined;
			const price = e.querySelector(PRICE_SELECTOR)
				? numerize(e.querySelector(PRICE_SELECTOR).textContent.trim())
				: undefined;

			return {
				name: name,
				link: link,
				thumb: thumb,
				country: country,
				region: region,
				average_rating: average_rating,
				ratings: ratings,
				price: price,
			};
		});
		return data;
	};

	// Set default state for the US
	if (countryCode.toLowerCase() === 'us' && stateCode === '') {
		stateCode = 'CA';
	}

	const BASE_URL = 'https://www.vivino.com';
	const SEARCH_PATH = '/search/wines?q=';
	const STATUS_FULL = 'FULL_DATA';
	const STATUS_ERROR_RESPONSE = 'RESPONSE_ERROR';
	const STATUS_ERROR_SHIP_TO = 'SHIP_TO_ERROR';
	const STATUS_ERROR_SHIP_TO_CONFIRM = 'SHIP_TO_CONFIRM_ERROR';
	const STATUS_ERROR_EXCEPTION = 'SOME_EXCEPTION';
	const PAUSE_MULTIPLIER = 15;

	const result = { vinos: [] };

	const browser = await puppeteer.launch({
		headless: true,
		defaultViewport: { width: 1920, height: 1040 },
		devtools: false,
		args: ['--start-maximized'],
	});

	const page = await browser.newPage();

	// need to set User Agent else an empty result
	// it seems they detect headless Chrome
	await page.setUserAgent(
		'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
	);

	// To save bandwidth block all types of requests except "document", "xhr", "fetch"
	await page.setRequestInterception(true);
	page.on('request', (request) => {
		if (['document', 'xhr', 'fetch', 'script'].includes(request.resourceType())) {
			request.continue();
		} else {
			request.abort();
		}
	});

	try {
		page.setDefaultNavigationTimeout(0);

		// load home page
		await page.goto(BASE_URL, { waitUntil: 'networkidle2' });

		// check the country and state
		let isDestinationRight = await isShipTo(countryCode, stateCode);
		if (!isDestinationRight) {
			// set country and state
			const resultSetShipTo = await setShipTo(countryCode, stateCode);
			if (resultSetShipTo) {
				await page.goto(BASE_URL, { waitUntil: 'networkidle2' });
				// check the country and state
				isDestinationRight = await isShipTo(countryCode, stateCode);
				if (!isDestinationRight) {
					console.log('"Ship To" changing can not be confirmed!');
					result.status = STATUS_ERROR_SHIP_TO_CONFIRM;
					return;
				}
			} else {
				console.log('"Ship To" was not changed!');
				result.status = STATUS_ERROR_SHIP_TO;
				return;
			}
		}

		let index = 1;
		let isNext = false;
		let pause = 0;

		do {
			isNext = false;
			const response = await page.goto(`${BASE_URL}${SEARCH_PATH}${name}&start=${index}`, {
				waitUntil: 'networkidle2',
			});

			if (response.ok()) {
				pause = 0;
				const pageItems = await page.evaluate(collectItems);
				if (pageItems.length) {
					console.log('Results were collected from the page:', index);
					result.vinos.push(...pageItems);
					index++;
					isNext = true;
				} else {
					// no more data
					result.status = STATUS_FULL;
				}
			} else if (response.status() === 429) {
				pause++;
				await page.waitForTimeout(pause * PAUSE_MULTIPLIER * 1000);
				console.log(`Waited for ${pause * PAUSE_MULTIPLIER} seconds on the page ${index}`);
				isNext = true;
			} else {
				// return some error info
				result.http_status = response.status(); // http status
				result.page_index = index; // index of the problem page
				result.status = STATUS_ERROR_RESPONSE;
			}
		} while (isNext);

		// Filter data
		result.vinos = result.vinos.filter((e) => {
			if (minPrice && (e.price || !noPriceIncluded) && e.price < minPrice) return false;
			if (maxPrice && e.price > maxPrice) return false;
			if (minRatings && e.ratings < minRatings) return false;
			if (maxRatings && e.ratings > maxRatings) return false;
			if (minAverage && e.average_rating < minAverage) return false;
			if (maxAverage && e.average_rating > maxAverage) return false;
			return true;
		});

		// console.log(JSON.stringify(result.vinos, null, 2));
	} catch (error) {
		result.status = STATUS_ERROR_EXCEPTION;
		result.message = error;
		console.log('Exception:', error);
	} finally {
		console.log('Finish!');

		// output results to the file
		const outFile = fs.createWriteStream('./output/'+name+'.json');
		outFile.write(JSON.stringify(result, null, 2));
		outFile.end();

		await browser.close();
	}
};

const args = minimist(process.argv.slice(2));
console.log(args);

const {
	name,
	country,
	state,
	minPrice,
	maxPrice,
	noPriceIncluded,
	minRatings,
	maxRatings,
	minAverage,
	maxAverage,
} = args;

run(
	name,
	country,
	state,
	minPrice,
	maxPrice,
	noPriceIncluded,
	minRatings,
	maxRatings,
	minAverage,
	maxAverage,
);