LoginSignup
7
5

More than 5 years have passed since last update.

Nokogiriを使ってるとよく出るエラー lib/nokogiri/xml/node_set.rb:164:in `attr': undefined method `attribute' for nil:NilClass (NoMethodError)

Last updated at Posted at 2016-04-19

※解決できたけど根本原因わからず。

※追記:コメントで@scivolaさんが解説してくださいました。

undefined method `attribute' for nil:NilClass (NoMethodError)
このエラーは初心者がnokogiriを使っている時によく出る。

html = open(URL,"User-Agent" => UserAgnet).read
doc = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
doc.css(".hoge").each do |row|
 puts row.css(".hogehoge img").attribute("src").value
end

こんな感じで img src を取ってくるときに、row.css(".hogehoge img") がnilだとNilClassにattributeメソッドが無いからエラーになると認識している。※間違ってたら教えて下さい。

大体こんな感じで書いてみるんだけど全然解決できない。

html = open(URL,"User-Agent" => UserAgnet).read
doc = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
doc.css(".hoge").each do |row|
  next if row.css(".hogehoge img").nil?
  begin
    puts row.css(".hogehoge img").attribute("src").value
  rescue => e
    p e
  end
end

#<NoMethodError: undefined method `attribute' for nil:NilClass>

どうしてだー。
解決方法を先に言うと、nil? でなく empty? でチェックできる。

html = open(URL,"User-Agent" => UserAgnet).read
doc = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
doc.css(".hoge").each do |row|
  next if row.css(".hogehoge img").empty?
  puts row.css(".hogehoge img").attribute("src").value
end

"nil:NilClass" これはNilクラスにattributeメソッド無いよーって言っているんじゃないのか?

html = open(URL,"User-Agent" => UserAgnet).read
doc = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
doc.css(".hoge").each do |row|
  p row.css(".hogehoge img").class if row.css(".hogehoge img").empty?
  puts row.css(".hogehoge img").attribute("src").value
end

emptyの時はclassを調べてみた。

Nokogiri::XML::NodeSet

まあそうなるか。。この辺がよくわからん。もっと勉強しなくては。

7
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5