每次都没有新记录将HTML解压缩到Rails中?

时间:2012-01-09 16:52:32

标签: html parsing nokogiri mechanize

我有以下代码,它尽可能简单地解析HTML表。

# Timestamp (Column 1 of the table)
page = agent.page.search("tbody td:nth-child(1)").each do |item|
  Call.create!(:time => item.text.strip)
end

# Source (Column 2 of the table)
page = agent.page.search("tbody td:nth-child(2)").each do |item|
  Call.create!(:source => item.text.strip)
end

# Destination (Column 3 of the table)
page = agent.page.search("tbody td:nth-child(3)").each do |item|
  Call.create!(:destination => item.text.strip)
end

# Duration (Column 4 of the table)
page = agent.page.search("tbody td:nth-child(4)").each do |item|
  Call.create!(:duration => item.text.strip)
end

虽然上面的代码运行良好,但它将每个“项目”视为新记录。因此,它为每个时间行添加一条记录,为每个源列添加另一条记录等。

让它循环上述代码但将四个项目添加到一个记录然后转到下一个记录的最简单方法是什么?

有关其他信息,请参阅显示我的数据库结构的迁移文件:

class CreateCalls < ActiveRecord::Migration
  def change
    create_table :calls do |t|
      t.datetime :time
      t.string :source
      t.string :destination
      t.string :duration

      t.timestamps
    end
  end
end

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

不是每次调用call.create而只是将所有源附加到字符串中,最后保存记录。

答案 1 :(得分:1)

考虑迭代每一行而不是每一列。

page = agent.page.search("table tbody tr").each do |row|
  time        = row.at("td:nth-child(1)").text.strip
  source      = row.at("td:nth-child(2)").text.strip
  destination = row.at("td:nth-child(3)").text.strip
  duration    = row.at("td:nth-child(4)").text.strip
  Call.create!(:time => time, :source => source, :destination => destination, :duration => duration)
end