2

这正在杀死我并在这里搜索,而大 G 让我更加困惑。

我遵循了 Nokogiri 上Railscasts #190上的教程,并且能够为自己编写一个不错的小解析器:

require 'rubygems'
require 'nokogiri'
require 'open-uri'

url = "http://www.target.com/c/movies-entertainment/-/N-5xsx0/Ntk-All/Ntt-wwe/Ntx-matchallpartial+rel+E#navigation=true&facetedValue=/-/N-5xsx0&viewType=medium&sortBy=PriceLow&minPrice=0&maxPrice=10&isleaf=false&navigationPath=5xsx0&parentCategoryId=9975218&RatingFacet=0&customPrice=true"

doc = Nokogiri::HTML(open(url))
puts doc.at_css("title").text
doc.css(".standard").each do |item|

title = item.at_css("span.productTitle a")[:title]
format = item.at_css("span.description").text
price = item.at_css(".price-label").text[/\$[0-9\.]+/]
link = item.at_css("span.productTitle a")[:href]

puts "#{title}, #{format}, #{price}, #{link}"

end

我对结果很满意,并且能够在 Windows 控制台中看到它。但是,我想将结果导出到 CSV 文件并尝试了多种方法(没有运气),我知道我遗漏了一些东西。我最新更新的代码(下载 html 文件后)如下:

require 'rubygems'
require 'nokogiri'
require 'csv'

@title = Array.new
@format = Array.new
@price = Array.new
@link = Array.new

doc = Nokogiri::HTML(open("index1.html"))
doc.css(".standard").each do |item|
@title << item.at_css("span.productTitle a")[:title]
@format << item.at_css("span.description").text
@price << item.at_css(".price-label").text[/\$[0-9\.]+/]
@link << item.at_css("span.productTitle a")[:href]
end

CSV.open("file.csv", "wb") do |csv|
csv << ["title", "format", "price", "link"]
csv << [@title, @format, @price, @link]
end

它工作并为我吐出一个文件,但只是最后一个结果。我按照Andrew!: WEB Scraping...的教程进行操作,并试图将我想要实现的目标与其他人的过程混合起来令人困惑。

我假设它正在遍历所有结果并且只打印最后一个。有人可以给我指点我应该如何循环这个(如果这是问题的话),以便所有结果都在它们各自的列中吗?

提前致谢。

4

2 回答 2

3

您将值存储在四个数组中,但在生成输出时并未枚举数组。

这是一个可能的修复:

CSV.open("file.csv", "wb") do |csv|
  csv << ["title", "format", "price", "link"]
  until @title.empty?
    csv << [@title.shift, @format.shift, @price.shift, @link.shift]
  end
end

请注意,这是一种破坏性操作,每次将值从数组中移出一个,因此最终它们都将为空。

有更有效的方法来读取和转换数据,但这有望满足您现在的需求。

于 2013-05-15T22:58:36.590 回答
2

您可以做几件事来以“Ruby 方式”编写更多内容:

require 'rubygems'
require 'nokogiri'
require 'csv'

doc = Nokogiri::HTML(open("index1.html"))
CSV.open('file.csv', 'wb') do |csv|
  csv << %w[title format price link]
  doc.css('.standard').each do |item|
    csv << [
      item.at_css('span.productTitle a')[:title]
      item.at_css('span.description').text
      item.at_css('.price-label').text[/\$[0-9\.]+/]
      item.at_css('span.productTitle a')[:href]
    ]
  end
end

如果没有示例 HTML,则无法对此进行测试,但是根据您的代码,它看起来可以工作。

请注意,在您的代码中,您使用的是实例变量。它们不是必需的,因为您没有定义要拥有实例的类。您可以改用本地值。

于 2013-05-21T06:02:42.513 回答