【问题标题】:Nokogiri: How can you exclude HTML attributes with certain class names?Nokogiri:如何排除具有某些类名的 HTML 属性?
【发布时间】:2012-03-21 06:33:55
【问题描述】:

如果我想在 Ruby 中使用 Nokogiri 解析 HTML 块,如下所示:

<th class="first">ancd</th>
<th>xyz</th>
<th>sdf</th>

如何排除包含某个类名的标签?在这种情况下是“第一个”。

【问题讨论】:

标签: ruby html-parsing nokogiri


【解决方案1】:

您可以使用 CSS 选择器:

doc.css('th:not(.first)')

在这个简单的例子中,你也可以使用xpath:

doc.xpath('//th[not(@class="first")]')

不同之处在于 xpath 要求类名完全匹配。如果您有可能拥有多个课程,例如&lt;th class="red first"&gt; 然后 CSS 选择器会识别它,但 xpath 不会(不会让它变得更复杂)。

编辑:仅供参考,如果您想要在一个元素上可能有多个类时可以选择一个类的xpath:

doc.xpath('//th[@class and contains(concat(" ",normalize-space(@class)," "), " first ")]')

通常 XPath 比 CSS 选择器灵活得多,但这是一种支持 CSS 的 HTML 边缘情况。

【讨论】:

  • 还能排除多个类名吗?例如,如果我有:&lt;th class='first'&gt;xxy&lt;/th&gt;&lt;th class='second'&gt;xxz&lt;/th&gt;
  • 当然,例如doc.xpath('//th[not(@class="first") and not(@class="second")]')
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 2021-10-13
  • 1970-01-01
  • 2011-10-11
  • 2012-10-08
  • 1970-01-01
相关资源
最近更新 更多