我一直在尝试使用Nokogiri和HTTParty抓取数据,并且可以成功地从网站上抓取数据并将其打印到控制台,但是我不知道如何在回购中将数据输出到xml文件。 / p>
现在代码如下:
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文件。对于如何正确解析数据的任何见解,我将不胜感激。
答案 0 :(得分:0)
我尝试将.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,然后将其输出保存到文件中。