2

これは私を殺し、ここで検索しています。大きな G は私をさらに混乱させています。

Railscasts #190 on Nokogiriのチュートリアルに従い、素敵な小さなパーサーを自分で作成することができました。

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