【问题标题】:How can I get only text in cheerio parser [duplicate]我怎样才能在 cheerio 解析器中只获取文本[重复]
【发布时间】:2022-11-20 00:58:43
【问题描述】:

如何在 cheerio 解析器中只获取文本

const cheerio = require("cheerio");
const axios = require("axios");

const getGPUCheckInfo = (html) => {
  const $ = cheerio.load(html);
  $("#summary > table > tbody > tr").each((i, element) => {
    console.log($(element).find("th").text());
  });
};

axios
  .get(
    "https://www.gpucheck.com/en-usd/gpu/nvidia-geforce-gtx-1050-ti/intel-core-i3-6100-3-70ghz/",
    {
      headers: {
        "user-agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
      },
    }
  )
  .then((response) => getGPUCheckInfo(response.data), console.log);

如何在没有其他标签的情况下只获得“综合得分”文本

实际上我有这个文本和标签内的文本

【问题讨论】:

标签: javascript node.js parsing cheerio


【解决方案1】:

您可以循环每个 th 的内容,并仅从文本节点获取值。

尝试这个:

$("#summary > table > tbody > tr").each((i, element) => {
    $(element).find("th").contents().each(function() {

        // get value from text node (nodeType 3)
        if (this.nodeType == 3) {
            console.log(this.nodeValue);
        }
    });
});

【讨论】:

  • 我发现过滤掉纯空白的文本节点通常是个好主意,如 here 所示。
猜你喜欢
  • 1970-01-01
  • 2016-11-24
  • 1970-01-01
  • 2021-04-22
  • 2023-01-12
  • 2019-01-12
  • 2018-03-02
  • 2017-03-29
  • 1970-01-01
相关资源
最近更新 更多