Parsing some results returned by nokogiri in ruby, getting an error message

Posted by Khat on Stack Overflow See other posts from Stack Overflow or by Khat
Published on 2010-04-03T04:19:13Z Indexed on 2010/04/03 4:23 UTC
Read the original article Hit count: 396

Filed under:
|

The following code returns an error:

require 'nokogiri'
require 'open-uri'

@doc = Nokogiri::HTML(open("http://www.amt.qc.ca/train/deux-montagnes/deux-montagnes.aspx"))
#@doc = Nokogiri::HTML(File.open("deux-montagnes.html"))
stations =  @doc.xpath("//area")
stations.each { |station| str = station
    reg = /href="(.*)" title="(.*)"/
        href = reg.match(str)[1]
    title = reg.match(str)[2]
    page = /.*\/(.*).aspx$/.match(href)[1]
    puts href
    puts title
    puts page
    base_url = "http://www.amt.qc.ca"
    complete_url = base_url + href
    puts complete_url
}

ERROR:

station_names_from_map.rb:9:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
        from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:213:in `block in each'
        from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:212:in `upto'
        from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:212:in `each'
        from station_names_from_map.rb:7:in `<main>'

shell returned 1

While this code works:

str = '<area shape="poly" alt="Deux-Montagnes" coords="59,108,61,106,65,106,67,108,67,113,65,115,61,115,59,113" href="/train/deux-montagnes/deux-montagnes.aspx" title="Deux-Montagnes">'

reg = /href="(.*)" title="(.*)"/
href = reg.match(str)[1]
title = reg.match(str)[2]
page = /.*\/(.*).aspx$/.match(href)[1]
puts href
puts title
puts page
base_url = "http://www.amt.qc.ca"
complete_url = base_url + href
puts complete_url

Any reason why?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about nokogiri