javascript - 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
解决方案
唯一需要改变的是这段代码。
安装的
cardText = $(元素).text();
利用
cardText += $(element).text();
推荐阅读
- sql - 在 athena 上工作时,数据在 redshift 外部表上显示为空
- sql - 嵌套连接查询
- deep-learning - 在 CNN 训练中跳过反向传播,以便在 Caffe 中进行更快的训练
- javascript - Java 脚本 XML 阅读器返回空 HTMLCollection
- latex - !LaTeX 错误:环境 threeparttable 未定义
- jquery - 如何使用按钮在两个 div 元素之间切换
- python - 数据框列列表中的随机换行符导致 KeyError
- reactjs - 在 redux 商店中更新字符串
- android - java.lang.NoClassDefFoundError:解析失败:Landroid/widget/Magnifier;
- c# - 在 C# 中使用 excelcnv.exe 或 ofc.exe 将 .xls 转换为 .xlsx