I want to make a request to website, get its html, and give it to cheerio. I need to get all the "href" attribute of all the elements with class ".thumb". I'm showing the results on the console and I just get undefined many times, I assume it's for each element found. I get undefined when trying to loop through any other element with tag or identifier, but if I don't loop and just get the first one the correct value is given.
function firstReq(){
req(url, (err,res,html)=>{
if(err){console.error(err);}
var $ = cheerio.load(html);
var arr = []
$("a").each(()=>{
console.log($(this).attr("href"));
});
});
}
I tried console.log(html) to check that the document was alright and it is. I also tried setting setTimeout on the iteration, maybe to give "request" and "cheerio" time to load the file, and still the same. I tried first downloading the html file from the url to my computer (outside of function, before call) and then passing it to cheerio, and still undefined.
It's my first personal project with Node and I'm very confused. Any help is appreciated.
You can use two ways here:
Arrow function
function firstReq(){
req(url, (err,res,html)=>{
if(err){console.error(err);}
var $ = cheerio.load(html);
var arr = []
$("a").each((i , elem)=>{
console.log($(elem).attr("href"));
});
});
}
Or function:
function firstReq(){
req(url, (err,res,html)=>{
if(err){console.error(err);}
var $ = cheerio.load(html);
var arr = []
$("a").each(function(){
console.log($(this).attr("href"));
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With