使用 Mechanize 和 Nokogiri 抓取网页并将数据存储在 XML 文档中

Scraping a webpage with Mechanize and Nokogiri and storing data in XML doc

我正在尝试使用 Mechanize 和 Nokogiri 抓取网站并将数据存储在 XML 中。我没有设置 Rails 项目,我只使用 Ruby 和 IRB。

我写了这个方法:

def mechanize_club
    agent = Mechanize.new
    agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
    form = agent.page.forms.first
    form.field_with(:name => 'codeLigue').options[0].select
    form.submit
    page2 = agent.get('http://www.rechercheclub.applipub-fft.fr/rechercheclub/club.do?codeClub=01670001&millesime=2015')
    body = page2.body
    html_body = Nokogiri::HTML(body)
    codeclub = html_body.search('.form').children("tr:first").children("th:first").to_i
    @codeclubs << codeclub
    filepath  = '/davidgeismar/Documents/codeclubs.xml'
    builder   = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
       xml.root {
          xml.codeclubs {
            @codeclubss.each do |c|
              xml.codeclub {
                xml.code_   c.code
              }
            end
          }
        }
    end
    puts builder.to_xml
  end

我的第一个问题是我不知道如何测试我的代码。 我在我的控制台中调用 ruby webscraper.rb,我认为文件已处理,但它不会在指定路径中创建 XML 文件。 然后,更具体地说,我很确定这段代码是错误的,因为我没有机会测试它。

基本上我想做的是多次提交表格:

 agent = Mechanize.new
      agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
      form = agent.page.forms.first
      form.field_with(:name => 'codeLigue').options[0].select
      form.submit

我觉得这段代码还可以,但我不希望它只selectoptions[0],我希望它select一个选项,然后抓取我需要的所有数据,然后返回页面,然后 select options[1]... 直到没有更多选项(我猜是迭代)。

the file is treated I think, but it doesnt create an xml file in the specified path.

您的代码中没有创建文件的内容。您打印一些输出,但不对 open or write 文件执行任何操作。

也许您应该阅读 IO and File 文档并查看您如何使用 filepath 变量?

第二个问题是您没有在任何地方调用您的方法。尽管它已被定义并且 Ruby 将看到它并解析该方法,但除非您调用该方法,否则它不知道您要用它做什么:

def mechanize_club
  ...
end

mechanize_club()