Ruby nokigiri使用的nil类的未定义方法

Ruby nokigiri使用的nil类的未定义方法,ruby,nokogiri,ruby-2.4,Ruby,Nokogiri,Ruby 2.4,我试图获取给定链接上的所有链接,但它给了我一个错误nil:NilClass的未定义方法'each' require 'nokogiri' def find_links(link) page = Nokogiri::HTML(open(link)) link_size = page.css('li') (0..link_size.length).each do |index| b = link_size[index]['href'] return b end end find_li

我试图获取给定链接上的所有链接,但它给了我一个错误nil:NilClass的未定义方法'each'

require 'nokogiri'
def find_links(link)
page = Nokogiri::HTML(open(link))
link_size = page.css('li')
(0..link_size.length).each do |index|
    b = link_size[index]['href']
    return b
end
end
find_links('http://code.tutsplus.com/tutorials/you-dont-know-anything-about-regular-expressions-a-complete-guide--net-7869').each do |url|
puts url
end

代码中有几个问题。请在下面找到解释:

def find_links(link)
  page = Nokogiri::HTML(open(link))
  link_size = page.css('li') 
  (0..link_size.length).each do |index|
     b = link_size[index]['href'] # You are expecting to get 'href' on list item which is wrong.
     return b # You shouldn't return from this block if you are expecting to get all the links. return from here will return from this method itself after first iteration. 
     # That's why you are getting nil error since link_size[index]['href'] doesn't have href attribute in first list item
  end
end
将代码更改为:(在线查找解释)


循环中出现了一个off by one错误–它应该在
link\u size.length-1
处停止。然而,有更好的方法来写这篇文章。
require 'nokogiri'
require 'open-uri'
def find_links(link)
  page = Nokogiri::HTML(open(link))
  # You want to iterate on anchor tags rather than list. 
  # See the use of `map`, it will return the array and since this is the last statement it will return from the method, giving all the links.
  # .css('li a') will give all the anchor tags which have list item in it's parent chain.
  page.css('li a').map { |x| x['href'] } 
end
find_links('http://code.tutsplus.com/tutorials/you-dont-know-anything-about-regular-expressions-a-complete-guide--net-7869').each do |url|
  puts url
end
require 'nokogiri'
require 'open-uri'
def find_links(link)
page = Nokogiri::HTML(open(link))
link_array = page.css('li')
(1..link_array.length).each do |f|
    a=Array.new.push(page.css('li a')[f]['href'])
    puts a
end
end
find_links('http://code.tutsplus.com/tutorials/you-dont-know-anything-about-regular-expressions-a-complete-guide--net-7869')