首页 > 解决方案 > Scraping text of an element and returning it in a function

问题描述

I'm trying to write a function that scrapes the text content of an element with the class "verdict" on different web pages. The problem is, I can't for the life of me figure out how to store this in a variable that can be returned. Here is my function. I've tried some wonky solutions, including putting cardText in an array and putting cardText in an array of objects, but to make things the least confusing I decided to revert back to my most vanilla attempt. When I do it this way, the function just returns an empty string.

    function cardQuotes(cardTitle){
  var cardText = "";  
// var cardTextArray = [];
request("http://localhost:3000/" + cardTitle.replace(/\s/g, ''), function(error, response, html) {


console.log("Does request fire?"); 
  var $ = cheerio.load(html);





  //DON'T NEED 'EACH'?
  $(".verdict").each(function(i, element) {


    cardText = $(element).text();

// cardTextArray.push({cardText: cardText});
  });



});

//Dammit I've tried so many things.  Turning it into an array, turning it into an array of objects.  
//Ugh.
//I can't seem to get the results of the scraping into a variable to be returned, that's the
//problem.
// return cardTextArray[0].cardText
return cardText;
}
//function ends here

标签: javascriptfunctionreturnscreen-scrapingcheerio

解决方案


唯一需要改变的是这段代码。

安装的

cardText = $(元素).text();

利用

cardText += $(element).text();


推荐阅读