0

我制作了一个基于 Mechanize 的解析器(ruby 文件)并将其放入 rails 应用程序(我是否正确?)。但我不知道如何让解析器将收集到的信息记录到数据库中。

解析器:

class PrintingHouses < ActiveRecord::Base
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://www.print-index.ru/default.aspx?p=82&gr=198')

loop do
  page.search('.goodname .goodname').each do |n|
    link = Mechanize::Page::Link.new(n, agent, page)
    new = link.click
    name = new.search('#ctl00_ctl00_BaseCentralRegion_CentralRegion_lblGoodName h1')
    address = new.search('.address')
    phone = new.search('.phone')
    email = new.search('.email')
    website = new.search('.www')
    puts name.text.center(100)
    print "Address: "
    puts address.text.strip
    print "Phone: "
    puts phone.text.strip
    print "email: "
    puts email.text.strip
    print "Website: "
    puts website.text.strip
  end
 break unless link = page.link_with(:text => " » " )
 page = link.click
 end
end
4

1 回答 1

0

我想我知道你的目标。

require 'mechanize'

agent = Mechanize.new
page = agent.get('http://www.print-index.ru/default.aspx?p=82&gr=198')

loop do
  page.search('.goodname .goodname').each do |n|
    link = Mechanize::Page::Link.new(n, agent, page)
    new = link.click
    name = new.search('#ctl00_ctl00_BaseCentralRegion_CentralRegion_lblGoodName h1')
    address = new.search('.address')
    phone = new.search('.phone')
    email = new.search('.email')
    website = new.search('.www')

    YourModelName.create(name: name.text.center(100), address: address.text.strip,
                         phone: phone.text.strip, email: email.text.strip, 
                         website: website.text.strip)


  end
 break unless link = page.link_with(:text => " » " )
 page = link.click
 end

只需确保您的模型名称和列名称正确且没有验证错误。

于 2013-08-15T09:58:39.357 回答