1const Apify = require('apify');
2
3Apify.main(async () => {
4
5 const input = await Apify.getInput();
6 const { busqueda, lugar } = input;
7 if (!busqueda || !lugar) {
8 throw new Error('Debes proporcionar "busqueda" y "lugar".');
9 }
10
11
12
13 const searchUrl = `https://www.yelp.com/search?find_desc=${encodeURIComponent(busqueda)}&find_loc=${encodeURIComponent(lugar)}`;
14 console.log(`Navegando a: ${searchUrl}`);
15
16
17 const browser = await Apify.launchPuppeteer({ headless: false });
18 const page = await browser.newPage();
19 await page.goto(searchUrl, { waitUntil: 'networkidle2' });
20
21
22 await autoScroll(page);
23
24
25 await page.waitForTimeout(30000);
26
27
28 await page.screenshot({ path: 'debug_yelp.png' });
29 console.log('Screenshot guardado: debug_yelp.png');
30
31
32 const results = await page.evaluate(() => {
33 const items = [];
34
35 const containers = document.querySelectorAll('ul.lemon--ul__373c0__1_cxs li');
36 containers.forEach(li => {
37
38 const nameElement = li.querySelector('a.css-166la90');
39 if (nameElement) {
40 const name = nameElement.innerText.trim();
41 const addressElement = li.querySelector('address');
42 const address = addressElement ? addressElement.innerText.trim() : 'No disponible';
43
44 const ratingElement = li.querySelector('div.i-stars__373c0__1T6rz');
45 const rating = ratingElement ? ratingElement.getAttribute('aria-label') : 'No disponible';
46 items.push({ name, address, rating });
47 }
48 });
49 return items;
50 });
51
52 console.log('Resultados extraídos:', results);
53 await browser.close();
54
55
56 if (results.length === 0) {
57 await Apify.pushData({ error: "No se extrajeron resultados. Verifica los selectores o la carga de la página." });
58 } else {
59 await Apify.pushData(results);
60 }
61});
62
63
64async function autoScroll(page) {
65 await page.evaluate(async () => {
66 await new Promise((resolve) => {
67 let totalHeight = 0;
68 const distance = 100;
69 const timer = setInterval(() => {
70 const scrollHeight = document.body.scrollHeight;
71 window.scrollBy(0, distance);
72 totalHeight += distance;
73 if (totalHeight >= scrollHeight - window.innerHeight) {
74 clearInterval(timer);
75 resolve();
76 }
77 }, 200);
78 });
79 });
80}