在 Puppeteer 中排除具有特定类的元素

3
我正在尝试使用Puppeteer解析的HTML大致如下:
<ul>
    <li class="title"> item 1 </li>
    <li class="title hide"> item 1 </li>
</ul>

我正在这样访问
  • 元素:
  • await page.$$eval("ul > li.title", nodes =>
        nodes.map(element => {
          return {
            //some attributes
          };
        })
      );
    

    要求的结果是仅检索没有 class=hide 的元素。不幸的是,hide 是一个除了所有 <li> 元素共享的 title 外的类。
    我该如何重构 Puppeteer 代码以排除带有 hide 类的元素?
    2个回答

    5

    :not(.hide)

    你应该使用:not() CSS 伪类来选择不包含 .hide 类的元素:
    await page.$$eval('ul > li.title:not(.hide)', nodes =>
      nodes.map(element => {
        return {
          // some attributes
        };
      })
    );
    

    .filter(e => !e.matches('.hide'))

    可以翻译为 “筛选出不匹配 '.hide' 选择器字符串的元素”。
    await page.$$eval('ul > li.title', nodes =>
      nodes.filter(e => !e.matches('.hide')).map(element => {
        return {
          // some attributes
        };
      })
    );
    

    4
    只需在选择器字符串中添加:not(.hide)即可:
    page.$$eval("ul > li.title:not(.hide)", nodes =>
    

    这很完美...我可以在哪里学到更多有关document.querySelector()的信息? - neo-technoker
    "querySelector" 接受任何有效的 CSS 选择器字符串 - 请参见此处(包括该页面左侧的链接),它们非常灵活。 - CertainPerformance

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接