【问题标题】:Excluding elements with certain classes in Puppeteer在 Puppeteer 中排除具有某些类的元素
【发布时间】:2019-04-22 07:24:57
【问题描述】:

我试图用 Puppeteer 解析的 HTML 看起来像这样:

<ul>
    <li class="title"> item 1 </li>
    <li class="title hide"> item 1 </li>
</ul>

我正在像这样访问li 元素:

await page.$$eval("ul > li.title", nodes =>
    nodes.map(element => {
      return {
        //some attributes
      };
    })
  );

扩展的结果是只检索没有class=hide 的元素。不幸的是,hide 是除 title 之外的一个类,它由所有 &lt;li&gt; 元素共享。

如何重构 Puppeteer 代码以排除具有 hide 类的元素?

【问题讨论】:

    标签: javascript css node.js google-chrome-devtools puppeteer


    【解决方案1】:

    只需将:not(.hide) 添加到您的选择器字符串中:

    page.$$eval("ul > li.title:not(.hide)", nodes =>
    

    【讨论】:

    • 这太完美了.. 有什么地方可以让我了解更多关于document.querySelector() 的内容吗?
    • querySelector 接受任何有效的 CSS 选择器字符串 - 请参阅 here(包括该页面左侧的链接),它们真的灵活
    【解决方案2】:

    :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'))

    另一方面,你也可以filter()你的nodes只包含.hide选择器字符串中不是matches()的元素:

    await page.$$eval('ul > li.title', nodes =>
      nodes.filter(e => !e.matches('.hide')).map(element => {
        return {
          // some attributes
        };
      })
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多