将html解析到Rails中,每次都没有新记录?
我有以下代码,它尽可能简单地解析 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
任何帮助都是值得赞赏的。
I have the following code which is parsing a HTML table as simply as possible.
# 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
Although the above code works well, it's treating each "item" as a new record. So it's adding a record for each of the time rows, another record for every one of the source column etc.
What is the simplest way of making it cycle the above code but adding the four items into one record and then moving on to the next record?
For additional info here is the migration file which shows my database structure:
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
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑迭代每一行而不是每一列。
Consider iterating over each row instead of each column.
不必每次都调用 call.create,只需将所有源附加到字符串中,然后在最后保存记录。
Instead of calling call.create everytime just append all the source to a string and the at the end save the record.