Creé un script usando axios y cheerio para obtener diferentes nombres de tiendas y sus enlaces asociados de las páginas amarillas y luego usé esos enlaces para raspar el teléfono y el correo electrónico de sus páginas internas. El guión va bien.
Lo que deseo hacer ahora es usar el enlace de la página siguiente para seguir capturando el contenido de las páginas siguientes también. Simplemente no puedo entender cómo aplicar la lógica de análisis y uso de las siguientes páginas dentro de la función getLinks() .
Por el momento esto es lo que estoy tratando con:
const axios = require('axios'); const cheerio = require('cheerio'); const startUrl = 'https://www.yellowpages.com/search?search_terms=Pizza&geo_location_terms=San+Francisco%2C+CA'; const host = 'https://www.yellowpages.com'; const getLinks = async (url,host,callback) => { const { data } = await axios.get(url); const $ = cheerio.load(data); $('[class="result"] a.business-name').each(function(){ let items = $(this).find('span').text(); let links = host + $(this).attr("href"); return callback(items,links); }); } const fetchContent = async (shopName,shopLink,callback) => { const { data } = await axios.get(shopLink); const $ = cheerio.load(data); let phone = $('.contact > p.phone').eq(0).text(); let email = $('.business-card-footer > a.email-business').eq(0).attr("href"); return callback(shopName,shopLink,phone,email); } async function scrapeData() { getLinks(startUrl,host,function(itemName,link){ fetchContent(itemName,link,function(shopName,shopLink,phone,email){ console.log({shopName,shopLink,phone,email}); }); }); } scrapeData();Los enlaces de la página siguiente a menudo están en [rel=next] , por lo que suele ser algo como esto:
async function get(url) { const { data } = await axios.get(url); const $ = cheerio.load(data); return $ } async function run(){ let url = 'https://www.yellowpages.com/search?search_terms=Pizza&geo_location_terms=San+Francisco%2C+CA' let $ = await get(url) // doSomething($) let href = $('[rel=next]').attr('href') while(href){ url = new URL(href, url).href $ = await get(url) // doSomething($) href = $('[rel=next]').attr('href') } }