1import { Actor, log } from 'apify';
2import { PlaywrightCrawler } from 'crawlee';
3import { extractCards } from './extract.js';
4import { entityIdFromUrl, htmlToText, parseOffersFromPage } from './offers.js';
5
6await Actor.init();
7
8const input = (await Actor.getInput()) ?? {};
9const {
10 queries = ['Lisbon'],
11 checkIn,
12 checkOut,
13 maxResultsPerQuery = 40,
14 language = 'en',
15 country = 'us',
16 includeVacationRentals = true,
17 includeOffers = false,
18 currency = 'USD',
19 proxyConfiguration: proxyInput,
20} = input;
21
22const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
23if ((checkIn && !DATE_RE.test(checkIn)) || (checkOut && !DATE_RE.test(checkOut))) {
24 throw new Error('checkIn / checkOut must be in YYYY-MM-DD format.');
25}
26if ((checkIn && !checkOut) || (!checkIn && checkOut)) {
27 throw new Error('Provide both checkIn and checkOut, or neither.');
28}
29if (checkIn && checkOut && checkOut <= checkIn) {
30 throw new Error('checkOut must be after checkIn.');
31}
32
33const maxResults = Math.min(Math.max(Number(maxResultsPerQuery) || 40, 1), 500);
34const proxyConfiguration = await Actor.createProxyConfiguration(proxyInput ?? { useApifyProxy: true });
35
36const buildQuery = (q) => {
37 let text = String(q).trim();
38 if (!/\b(hotels?|hostels?|resorts?|accommodations?|stays?)\b/i.test(text)) text = `hotels in ${text}`;
39 if (checkIn && checkOut) text += ` from ${checkIn} to ${checkOut}`;
40 return text;
41};
42
43
44const cur = String(currency || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 3);
45const varint = (n) => { const o = []; while (n > 127) { o.push((n & 127) | 128); n >>>= 7; } o.push(n); return o; };
46const ld = (tag, bytes) => [tag, ...varint(bytes.length), ...bytes];
47const dateBytes = (s) => { const [y, m, d] = s.split('-').map(Number); return [0x08, ...varint(y), 0x10, ...varint(m), 0x18, ...varint(d)]; };
48function makeTs() {
49 const parts = [0x08, 0x01];
50 if (checkIn && checkOut) {
51 const n = Math.round((Date.parse(checkOut) - Date.parse(checkIn)) / 864e5);
52 const dates = [...ld(0x12, [...ld(0x0a, dateBytes(checkIn)), ...ld(0x12, dateBytes(checkOut))]), 0x18, ...varint(n)];
53 parts.push(...ld(0x1a, ld(0x12, dates)));
54 }
55 if (cur.length === 3) parts.push(...ld(0x2a, ld(0x0a, ld(0x3a, [...Buffer.from(cur)]))));
56 return Buffer.from(parts).toString('base64url');
57}
58const tsParam = cur.length === 3 ? `&ts=${makeTs()}` : '';
59
60const requests = queries
61 .map((q) => String(q || '').trim())
62 .filter(Boolean)
63 .map((q) => ({
64 url: `https://www.google.com/travel/search?q=${encodeURIComponent(buildQuery(q))}&hl=${encodeURIComponent(language)}&gl=${encodeURIComponent(country)}${tsParam}`,
65 uniqueKey: `${q}|${checkIn}|${checkOut}|${language}|${country}|${cur}`,
66 userData: { query: q },
67 }));
68
69if (!requests.length) throw new Error('Input "queries" must contain at least one location, e.g. "Lisbon".');
70
71let budgetReached = false;
72
73
74async function getOffers(page, card) {
75 const empty = { offers: [], lowestOffer: null, typicalPriceRange: null, googleHotelUrl: null };
76 const id = card.detailUrl ? entityIdFromUrl(card.detailUrl) : null;
77 if (!id) return empty;
78 const base = `https://www.google.com/travel/hotels/entity/${id}`;
79 const q = new URL(card.detailUrl, 'https://www.google.com').searchParams.get('q') || '';
80 const url = `${base}/prices?q=${encodeURIComponent(q)}&hl=${encodeURIComponent(language)}&gl=${encodeURIComponent(country)}${tsParam}`;
81 for (let attempt = 0; attempt < 2; attempt += 1) {
82 try {
83 const res = await page.request.get(url, { timeout: 30000 });
84 if (!res.ok()) continue;
85 const html = await res.text();
86 if (/\/sorry\/|unusual traffic/i.test(html.slice(0, 5000))) return { ...empty, googleHotelUrl: base };
87 const { offers, typicalPriceRange } = parseOffersFromPage(htmlToText(html));
88 const lowest = offers.reduce((m, o) => (o.price != null && (!m || o.price < m.price) ? o : m), null);
89 return {
90 offers,
91 lowestOffer: lowest ? { provider: lowest.provider, price: lowest.price, currency: lowest.currency } : null,
92 typicalPriceRange,
93 googleHotelUrl: base,
94 };
95 } catch (e) {
96 log.debug(`Offers attempt ${attempt + 1} failed for ${card.name}: ${e.message}`);
97 }
98 }
99 return { ...empty, googleHotelUrl: base };
100}
101
102const crawler = new PlaywrightCrawler({
103 proxyConfiguration,
104 maxConcurrency: 2,
105 maxRequestRetries: 4,
106 navigationTimeoutSecs: 45,
107 useSessionPool: true,
108 persistCookiesPerSession: false,
109 sessionPoolOptions: { maxPoolSize: 20, sessionOptions: { maxUsageCount: 5 } },
110 preNavigationHooks: [async (_ctx, gotoOptions) => { gotoOptions.waitUntil = 'domcontentloaded'; }],
111 async errorHandler({ session }) { session?.retire(); },
112 requestHandlerTimeoutSecs: 600,
113 launchContext: { launchOptions: { locale: `${language}-${country.toUpperCase()}` } },
114 async requestHandler({ page, request }) {
115 const { query } = request.userData;
116 await page.waitForLoadState('networkidle', { timeout: 30000 }).catch(() => {});
117
118
119 const blocked = page.url().includes('/sorry/')
120 || await page.locator('text=/unusual traffic/i').count() > 0;
121 if (blocked) {
122 request.noRetry = true;
123 throw new Error(`Google showed a CAPTCHA for "${query}". Skipping this query (CAPTCHAs are not bypassed).`);
124 }
125
126 await page.waitForSelector('h2', { timeout: 30000 });
127
128 const seen = new Set();
129 let position = 0;
130 let pageNo = 1;
131
132 while (position < maxResults && !budgetReached) {
133 const cards = await page.evaluate(extractCards);
134 const fresh = [];
135 for (const card of cards) {
136 if (position + fresh.length >= maxResults) break;
137 const key = `${card.name}|${card.priceText}`;
138 if (seen.has(key)) continue;
139 seen.add(key);
140 if (!includeVacationRentals && card.type === 'vacation_rental') continue;
141 fresh.push(card);
142 }
143 const offerData = new Array(fresh.length).fill(null);
144 if (includeOffers) {
145 for (let i = 0; i < fresh.length; i += 5) {
146 const chunk = await Promise.all(fresh.slice(i, i + 5).map((c) => getOffers(page, c)));
147 chunk.forEach((d, j) => { offerData[i + j] = d; });
148 }
149 }
150 let added = 0;
151 for (let i = 0; i < fresh.length; i += 1) {
152 const card = fresh[i];
153 position += 1;
154 added += 1;
155 const od = offerData[i] || {};
156 if (cur.length === 3) {
157 card.currency = cur;
158 if (od.offers) od.offers = od.offers.map((o) => ({ ...o, currency: cur }));
159 if (od.lowestOffer) od.lowestOffer = { ...od.lowestOffer, currency: cur };
160 }
161 const item = {
162 query,
163 position,
164 ...card,
165 ...od,
166 checkIn: checkIn ?? null,
167 checkOut: checkOut ?? null,
168 detailUrl: card.detailUrl ? new URL(card.detailUrl, 'https://www.google.com').href : null,
169 searchUrl: request.url,
170 scrapedAt: new Date().toISOString(),
171 };
172 const charge = await Actor.pushData(item, 'hotel-result');
173 if (charge?.eventChargeLimitReached) {
174 budgetReached = true;
175 log.info('The maximum charge set for this run was reached. Stopping.');
176 break;
177 }
178 if (item.offers?.length) {
179 const c2 = await Actor.charge({ eventName: 'hotel-offers' });
180 if (c2?.eventChargeLimitReached) {
181 budgetReached = true;
182 log.info('The maximum charge set for this run was reached. Stopping.');
183 break;
184 }
185 }
186 }
187 log.info(`"${query}" page ${pageNo}: +${added} results (total ${position}).`);
188 if (position >= maxResults || budgetReached) break;
189
190
191 await page.mouse.wheel(0, 20000).catch(() => {});
192 await page.waitForTimeout(1200);
193 let next = page.getByRole('button', { name: /^Next$/ }).last();
194 if (!(await next.count()) || !(await next.isVisible().catch(() => false))) {
195 next = page.locator('span:text-is("Next")').last();
196 }
197 if (!(await next.count()) || !(await next.isVisible().catch(() => false))) break;
198 const before = (await page.$$eval('h2', (hs) => hs.map((h) => h.innerText).join('|')));
199 await next.scrollIntoViewIfNeeded();
200 await next.click();
201 await page.waitForFunction(
202 (prev) => [...document.querySelectorAll('h2')].map((h) => h.innerText).join('|') !== prev,
203 before,
204 { timeout: 20000 },
205 ).catch(() => {});
206 await page.waitForLoadState('networkidle', { timeout: 20000 }).catch(() => {});
207 pageNo += 1;
208 if (added === 0) break;
209 }
210 },
211 failedRequestHandler({ request, error }) {
212 log.error(`Query "${request.userData.query}" failed: ${error?.message}`);
213 },
214});
215
216await crawler.run(requests);
217await Actor.exit();