我正在进行网络抓取工作,只需要显示带有标题,链接和摘要的文章。
如果其中任何一个为null,我不想找到它们。这是我的JS代码:
results.link = $(element).find("a").attr("href");
results.title = $(element).find("a").text().trim();
results.summary = $(element).find("p.summary").text().trim();
我已经通过mongo文档尝试了存在和类型的变体,但似乎无法提取我需要的值。任何帮助表示赞赏。
// Route for getting all Articles from the db
app.get("/articles", function (req, res) {
// Grab every document in the Articles collection that has a distinct title
db.Article.distinct("results.title")
.then(function (dbArticle) {
// If we were able to successfully find Articles, send them back to the client
res.json(dbArticle);
})
.catch(function (err) {
// If an error occurred, send it to the client
res.json(err);
});
});
答案 0 :(得分:0)
您可以检查空值
// return true if value is null else false
function isNullOrEmpty(data){
if(data == null || data == "" || data.trim().length == 0){
return true;
}
return false;
}
var link = $(element).find("a").attr("href");
var title = $(element).find("a").text().trim();
var summary = $(element).find("p.summary").text().trim();
// assign value only if all of them has some value
if( !isNullOrEmpty(link) && !isNullOrEmpty(title) && !isNullOrEmpty(summary)){
results.link = link;
results.title = title;
results.summary = summary
}