我正在尝试编写一个函数,该函数在不同的网页上使用“ verdict”类来抓取元素的文本内容。问题是,我一生都无法弄清楚如何将其存储在可以返回的变量中。这是我的功能。我尝试了一些奇怪的解决方案,包括将cardText放置在数组中以及将cardText放置在对象数组中,但是为了使事情变得最少混乱,我决定恢复到最原始的尝试。当我这样做时,该函数只会返回一个空字符串。
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
仅需要更改的是这段代码。
insted of
cardText = $(element).text();
使用
cardText + = $(element).text();