【问题标题】:How do I scrape a website and output data to xml file with Nokogiri?如何使用 Nokogiri 抓取网站并将数据输出到 xml 文件?
【发布时间】:2019-07-06 00:16:01
【问题描述】:

我一直在尝试使用 Nokogiri 和 HTTParty 抓取数据,并且可以成功地从网站上抓取数据并将其打印到控制台,但我不知道如何将数据输出到 repo 中的 xml 文件。

现在代码如下所示:

class Scraper

  attr_accessor :parse_page

  def initialize
    doc = HTTParty.get("https://store.nike.com/gb/en_gb/pw/mens-nikeid-lifestyle-shoes/1k9Z7puZoneZoi3?ref=https%253A%252F%252Fwww.google.com%252F")
    @parse_page ||= Nokogiri::HTML(doc)
  end

  def get_names
    item_container.css(".product-display-name").css("p").children.map { |name| name.text }.compact
  end

  def get_prices
    item_container.css(".product-price").css("span.local").children.map { |price| price.text }.compact
  end

  private

  def item_container
    parse_page.css(".grid-item-info")
  end

  scraper = Scraper.new
  names = scraper.get_names
  prices = scraper.get_prices

  (0...prices.size).each do |index|
    puts " - - - Index #{index + 1} - - -"
    puts "Name: #{names[index]} | Price: #{prices[index]}"
  end

end

我尝试将 .each 方法更改为包含 File.write() ,但它所做的只是将输出的最后一行写入 xml 文件。对于如何正确解析数据的任何见解,我将不胜感激,我是抓取新手。

【问题讨论】:

    标签: ruby xml parsing web-scraping


    【解决方案1】:

    我尝试将 .each 方法更改为包含 File.write(),但它所做的只是将输出的最后一行写入 xml 文件。

    File.write 方法是否在 each 循环内?我猜这里发生的事情是您在每次迭代时都覆盖了文件,这就是为什么您只看到最后一行。

    尝试将each 循环放在File.open 方法的块中,例如:

    File.open(yourfile, 'w') do |file|
      (0...prices.size).each do |index|
        file.write("your text")
      end
    end
    

    我还建议阅读Nokogiri::XML::Builder,然后将其输出保存到文件中。

    【讨论】:

    • 我认为已经完成了。我对范围界定感到困惑。谢谢你!
    猜你喜欢
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多