【问题标题】:Delete Nodes from a HTML table using Nokogiri使用 Nokogiri 从 HTML 表中删除节点
【发布时间】:2011-08-16 14:05:38
【问题描述】:

我一直在为这个问题摸不着头脑。在我开始思考之前帮助我。

我有一个 html 文档,其中包含一个事件表,其中包含“In”和“Out”作为列的一部分。记录可以是 In 或 Out 事件。我不想只获取“In”列中具有值的行,然后将文本保存在具有相同属性的事件模型中。下面的代码是我所拥有的,它返回“0”。

#!/usr/bin/env ruby

require 'rubygems'
require 'nokogiri'


doc = Nokogiri::HTML <<-EOS
  <table><thead><th>Reference</th><th>Event Date</th><th>Event Details</th><th>In</th><th>Out</th></thead><tbody><tr><td>BCE16</td><td>2011-08-16 11:14:52</td><td>Received from Arap Moi</td><td>30.00</td><td></td></tr><tr><td>B07K2</td><td>2011-08-16 11:10:06</td><td>Sent out to John Doe.</td><td>&nbsp;</td><td>-50.00</td></tr></tbody><tfoot></tfoot></table>
EOS


minus_received = doc.xpath('//td[contains(text(), "Received from")]').each do |node| 
  node.parent.remove
end

p minus_received.to_s

人类可读的标记

<table>
  <thead>
    <th>Reference</th>
    <th>Event Date</th>
    <th>Event Details</th>
    <th>In</th>
    <th>Out</th>
  </thead>

  <tbody>
  <tr>
    <td>BCE16</td>
    <td>2011-08-16 11:14:52</td>
    <td>Received from Arap Moi.</td>
    <td>30.00</td>
    <td></td>
  </tr>
  <tr>
    <td>B07K2</td>
    <td>2011-08-16 11:10:06</td>
    <td>Sent out to John Doe.</td>
    <td>&nbsp;</td>
    <td>-50.00</td>
  </tr>
  </tbody>
  <tfoot></tfoot>
</table>

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby search nokogiri nodes


    【解决方案1】:

    您正在输出 .each 的值 - 如果您在每次调用完成后查看 doc,则 html 仅包含标题和 John Doe。

    【讨论】:

    • 感谢 Briggs 指出这一点。那个小无赖真的把我的脑子弄乱了。
    猜你喜欢
    • 2010-12-15
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多