javascript - 是否可以在 map 函数的 return 语句中检查 DOM 元素的 NULL 吗?
问题描述
我有一个小的网络抓取 scipt 正在运行,它适用于大多数项目,直到网站上的模式发生变化。
网站被抓取(使用条款和 robots.txt 遵守): https ://www.studycheck.de/hochschulen/fhvr-bayern/bewertungen
这是一个德语页面,上面有学生对他们的大学/课程的评论。
在下面的代码中,我抓取了一个包含每个学生评分所需的所有内容的整个 div 容器,并将其拆分为 puppeteers 页面评估函数的 return 语句中的 map 函数中的构造函数。
构造函数:
function Corpus(course, rating, author, text, date){
this.course = course;
this.rating = rating;
this.author = author;
this.text = text;
this.date = date;
}
函数占用 div 并返回单个 css-selector 项的属性:
var getReview = await page.evaluate(() => {
//this querySelectorAll get's the 4 review divs per page
let reviewBlock = Array.from(document.querySelectorAll("div [class*='report-item-boxed']"))
//now I split up the 5 items I need for my constructor
return reviewBlock.map(block => [
block.querySelector(".item-course-title a").textContent.trim(),
block.querySelector("div .rating-value").textContent.trim(),
block.querySelector(".item-author").innerText,
block.querySelector("p.item-text").innerText.trim(),
block.querySelector('span.item-date').innerText
]);
});
这适用于特定年龄的所有评论。这些深入分页的旧评论没有元素“div .rating-value”,因此 .textcontent 返回 null 并且代码中断。
我试图放一个 if(css-element == null){than return "null"} else {map the textcontent as normal) 但它抛出一个错误,即 if 是那个地方的意外标记......
我试图了解这些关于 SO 的帖子是否是我的问题,但无法弄清楚。
我应该在 return 语句之前做任何错误处理然后返回一个对象吗?
我非常感谢任何提示如何解决该问题并在未找到选择器/它的属性值为空的情况下返回占位符值。
谢谢!!!
解决方案
并不是说这是最干净的解决方案,而是为了解决您的问题:
这个:
return reviewBlock.map(block => [
block.querySelector(".item-course-title a").textContent.trim(),
block.querySelector("div .rating-value").textContent.trim(),
block.querySelector(".item-author").innerText,
block.querySelector("p.item-text").innerText.trim(),
block.querySelector('span.item-date').innerText
]);
相当于:
return reviewBlock.map(block => {
// So you can make your if conditions here,
// and build the array dynamically before returning it.
return [
block.querySelector(".item-course-title a").textContent.trim(),
block.querySelector("div .rating-value").textContent.trim(),
block.querySelector(".item-author").innerText,
block.querySelector("p.item-text").innerText.trim(),
block.querySelector('span.item-date').innerText
]
});
推荐阅读
- firebase - 无法添加 Firebase 云消息发布后
- reactjs - React 中的清理引用问题
- adb - windows上是否有任何adb等待设备超时方法
- c - 有没有办法让 snprintf 在丢弃的字符处恢复?
- javascript - firebase.storage() 给出未捕获的类型错误
- xamarin.forms - Xamarin Forms 5.0.0.2012 热重载不起作用
- rust - 如何从 Rust 的 MD-5 (MD5) crate 中获取十六进制字符串?
- node.js - 为什么 npm pack 和 npm install 会产生两个不同的 package.json 文件?
- android - 从 Android 的 Google Drive 中存储的 Excel 文件中读取内容
- excel - 通过对话框将当前工作簿另存为单独的 Excel 工作簿