Open CharlieRoldan opened 3 years ago
// DEFINICIONES
const puppeteer = require('puppeteer'); const chalk = require('chalk'); const request = require('request-promise'); const cheerio = require('cheerio');
//BUSCADOR
console.log('');
console.log(chalk.yellow('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'));
console.log(chalk.white('SEARCH MERCADOLIBRE 1.0 by Charlie '));
console.log(chalk.yellow('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'));
console.log('');
const prompt = require('prompt-sync')();
const name = prompt('Palabra clave a buscar? : ');
console.log('');
console.log(chalk.white(Resultados cargando... ${name}
));
console.log('');
console.log(chalk.white('Total de productos encontrados'));
console.log('');
//FIN DE BUSCADOR console.log(chalk.yellow('-------------------------------------------------------------------'));
//NUEVA DEFINICION
const URL = (https://listado.mercadolibre.com.ar/${name}#D[A:${name}]
);
(async () => {
const response = await request (URL);
// console.log(response);
let $ = cheerio.load(response);
let productosencontrados = $('div[class="ui-search-search-result"] > span').text();
console.log(productosencontrados);
console.log(chalk.yellow('-------------------------------------------------------------------'));
})()
// TRAE LOS RESULTADOS DE TODOS LOS "productos" DE LA PRIMER PAGINA (PARA NO TRABARLO)
function runSearch (pagesToScrape) {
return new Promise(async (resolve, reject) => {
try {
if (!pagesToScrape) {
pagesToScrape = 1;
}
const browser = await puppeteer.launch();
const page = (await browser.pages())[0];
await page.goto(https://listado.mercadolibre.com.ar/${name}#D[A:${name}]
);
//await page.goto("https://celulares.mercadolibre.com.ar/apple/iphone/4g-lte/_Desde_51");
//await page.goto("https://celulares.mercadolibre.com.ar/apple/iphone/4g-lte/_Desde_101");
let currentPage = 1;
let urls = [];
while (currentPage <= pagesToScrape) {
let newUrls = await page.evaluate(() => {
let results = [];
let producto = Array.from(document.querySelectorAll('h2.ui-search-item__title'));
producto.forEach((item) => {
results.push({
VENDO: item.innerText,
});
});
let precio = document.querySelectorAll('div.ui-search-price__second-line');
precio.forEach((item) => {
results.push({
PRECIO: item.textContent,
});
});
return results;
});
urls = urls.concat(newUrls);
if (currentPage < pagesToScrape) {
await Promise.all([
await page.click('a.andes-pagination__link.ui-search-link'),
await page.waitForSelector('h2.ui-search-item__title')
])
}
currentPage++;
}
browser.close();
return resolve(urls);
} catch (e) {
return reject(e);
}
})
} runSearch().then(console.log).catch(console.error);
El código está armado en Nodejs usando fundamentalmente dos librerías (PUPETEER & CHEERIO). Próximo desafío: