Cheerio 获取嵌套的子元素文本

问题描述

我是 html/css 的新手。

我正在尝试遍历搜索结果的每个 div 并过滤掉具有特定文本的那些(但文本嵌套很深)。

我就是这样做的。我加载了整个 html。我正在尝试获取基于选择器的数组元素。这是通过以下方式完成的:

const elements = $(
      "div.results.row > div[data-attr]",);

这给了我一个包含 div 属性(设置或不设置值)的 data-attr 结果列表。

但是,根据结果数组,我还需要进一步获取其中一个元素中的文本。结果元素示例:

<div data-attr="some random attrib here for each element">
  <span>
    <div>
    </div>
    <div>
      <div>
        <h2>
          <span class="unique class name here but same for all">some deep child text i need to extract</span>
        </h2>
      </div>
    </div>
  </span>
</div>

这是我当前代码的工作方式:

const remainingElements = elements.filter((_,element) => {
      return !!element.attribs["data-attr"];
    });

它返回包含 data-attr 中实际值的列表(某些元素中没有值,所以我不得不过滤掉这些值)。

但是如前所述,我需要获取文本,以便我可以进一步过滤掉某些文本的结果。

我试过了,但我得到空字符串:

const remainingElements = elements.filter((_,element) => {
console.log(
        $(element)
        .children(".unique.class.name.here.but.same.for.all")
        .text(),);
      return !!element.attribs["data-attr"];
    });

那么如何在现有元素上使用选择器?还是我做错了?

解决方法

像这样过滤带有某些文本的 div?

$("div.results.row > div[data-attr]").get().filter(el => !$(el).text().match(/not me!/))