En el siguiente código, trato de devolver arr con detalles, pero creo que está vacío debido a la solicitud. ¿Qué puedo hacer para que esto funcione?
module.exports = function getWeather(country) { var arr = []; var pageToVisit = "https://www.timeanddate.com/weather/" + country; console.log("Visiting page " + pageToVisit); request(pageToVisit, function(error, response, body) { if (error) { console.log("Error: " + error); } // Check status code (200 is HTTP OK) console.log("Status code: " + response.statusCode); if (response.statusCode === 200) { // Parse the document body var $ = cheerio.load(body); console.log("Page title: " + $('title').text()); $('div.bk-focus__qlook').each(function(index) { var title = $(this).find('div.h2').text().trim(); //var link = $(this).find('div.h1').attr('href'); console.log('title: ' + title); //console.log(link); arr.push(title) }); } }); return arr; } El arr siempre está vacío y no puedo agregar el title al arr . ¿Cómo puedo esperarlo?
Escribiría una función:
function pagetovisit( parameters if necessary) { // logic whatever you want to do } async function asyncCall() { /// stock the return value in a var const result = await pagetovisit(); console.log(result); // expected output: "resolved" }No parece que ese sitio web utilice una API meteorológica pública. Parece una página HTML renderizada previamente que se carga desde el servidor.
La información de la API incluso incluye el clima: https://www.timeanddate.com/services/api/
Si tuviera que devolver una lista de texto raspado, necesitaría hacer que su función sea asíncrona y devolver la Promise de esta manera:
const parseHTML = (htmlText) => new DOMParser().parseFromString(html, 'text/html'); const getWeather = async (country, city) { var pageToVisit = `https://www.timeanddate.com/weather/${country}/${city}` console.log(`Visiting page: ${pageToVisit}`); return fetch(pageToVisit, { method: 'GET', headers: { 'Content-Type': 'text/html', } }) .then(response => response.text()) .then(parseHTML) .then(doc => [...doc.querySelectorAll('div.bk-focus__qlook')].map(qlook => qlook.querySelector('div.h2').textContent.trim())); }; module.exports = getWeather; // https://www.timeanddate.com/weather/usa/chicago const weather = await getWeather('usa', 'chicago'); // Should not be emptyMe desharía de este sitio web, porque:
gracias a todos, utilizo callback fun y funciona.
var cheerio = require('cheerio'); var URL = require('url-parse'); var express = require('express'); var country="canada"; module.exports= function getWeather(country,callback){ var arr=[]; arr.push(country) var pageToVisit = "https://www.timeanddate.com/weather/"+country; console.log("Visiting page " + pageToVisit); request(pageToVisit, function(error, response, body) { if(error) { callback(error); } // Check status code (200 is HTTP OK) console.log("Status code: " + response.statusCode); if(response.statusCode === 200) { // Parse the document body var $ = cheerio.load(body); console.log("Page title: " + $('title').text()); $('div.bk-focus__qlook').each(function( index ) { var temp = $(this).find('div.h2').text().trim(); var wind = $(this).find('p').text().trim(); var index=wind.search("Wind") wind=wind.substring(index); arr.push(temp) arr.push(wind) }); } callback(null, arr); }); } getWeather(country, function(err, result){ if(err) {console.log(err); } else { console.log(result); } });