首页 > 解决方案 > 是否可以在 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 的帖子是否是我的问题,但无法弄清楚。

返回内部的Javascript if语句

返回语句中的空值检查

我应该在 return 语句之前做任何错误处理然后返回一个对象吗?

我非常感谢任何提示如何解决该问题并在未找到选择器/它的属性值为空的情况下返回占位符值。

谢谢!!!

标签: javascriptnode.jspuppeteer

解决方案


并不是说这是最干净的解决方案,而是为了解决您的问题:

这个:

      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
      ]

    });

推荐阅读