6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby: スクレイピングで No method Errorが出たあなたに

Last updated at Posted at 2018-01-15

はじめに

題名の通りです。
スクレイピングをしていて、あっている気がするけど、なぜかNoMethodErrorがでるといった場合に見ていただければいいかなと思います。

自分の環境でそのエラーを再現して見ました。次のようなエラー文がおそらくでていることでしょう。

Scraping.rb
scraping.rb:36:in `<main>`: undefined method `get_attribute` for #<Nokogiri::XML::NodeSet:0x007fa32bc11710> (NoMethodError)

get_attributeの部分は、もしかしたらinner_textや、textかもしれません。

解決策

~~.search() の部分を **~~.at()**に変更して見ましょう。
コードベースで見ると、

elements = page.search()
この部分を

     ↓↓↓↓↓

element = page.at()
こうです

単数・複数は、返り値が一つしかないか、複数ある可能性があるかによって変更しています。
searchは、 配列が返り値 として返ってくる為に、eachや**(配列オブジェクト)[0]**などを使って、配列の中の要素にアクセスしないといけないからです。

どんな時に起こるの?

自分がよくこのエラーに遭遇するときは、nextボタンを押すときです。
ついつい癖でsearchを使ってしまいます。
image.png

しばらくは同じエラーを出さないとは思うのですが、同じようにつまずいた人にとって、参考になれば嬉しいです。

6
2
0

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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?