我正在尝试抓取有关网站新专辑发行的信息,我正在通过 Nokogiri 处理这个问题。这个想法是创建一个漂亮的数组,其中包含这样的项目
[
0 => ['The Wall', 'Pink Floyd', '1979'],
1 => ['Led Zeppelin I', 'Led Zeppelin', '1969']
]
这是我当前的代码。我是一个完全的红宝石新手,所以任何建议都将不胜感激。
@events = Array.new()
# for every date we encounter
doc.css("#main .head_type_1").each do |item|
date = item.text
# get every albumtitle
doc.css(".albumTitle").each_with_index do |album, index|
album = album.text
@events[index]['album'] = album
@events[index]['release_date'] = date
end
#get every artistname
doc.css(".artistName").each do |artist|
artist = artist.text
@events[index]['artist'] = artist
end
end
puts @events
PS我试图抓取的页面格式有点奇怪:
<tr><th class="head_type_1">20 October 1989</th></tr>
<tr><td class="artistName">Jean Luc-Ponty</td><td class="albumTitle">Some example album</td></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
<tr><th class="head_type_1">29 October 1989</th></tr>
<tr><td class="artistName">Some Other Artist</td><td class="albumTitle">Some example album</td></tr>
当我尝试在 ruby 解释器中运行它时,出现以下错误:
get_events.rb:25:in `block (2 levels) in <main>': undefined method `[]=' for nil:NilClass (NoMethodError)
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:239:in `block in each'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `upto'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `each'
from get_events.rb:23:in `each_with_index'
from get_events.rb:23:in `block in <main>'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:239:in `block in each'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `upto'
from /Users/adrian/.rvm/gems/ruby-1.9.3-p286/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `each'
from get_events.rb:18:in `<main>'
我该如何解决?