0
1

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.

rails 発展その7 スクレイピング

Posted at

スクレイピングとはwebページのHTMLから情報を抜き出す方法です。
データの集計にも役立ちます。

railsスクレイピングの基本

gemfile
  gem 'mechanize'
 # このgemでスクレイピングができるようになります。
ターミナル
  $ bundle install
   #忘れずに反映します。
controller

  # 上から順にスクレイピングの基本となるコード例一覧です。

   sample = Mechanize.new 
   # Mechanizeを使ってスクレイピングをするには、Mechanizeクラスのインスタンスを生成します。

   page = sample.get("http://~~(アドレス)") 
   # getメソッドでHTMLを取得

   ele = page.search('h2 a')
   # searchメソッドでh2とaの要素を検索
   
   puts ele.inner_text
   # inner_textメソッドで得られたHTML情報のテキストを取得する
  
   puts ele.get_attribute('href') 
   # get_attributeメソッドでhrefの取り出し
   # puts ele[:href]としても良い
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?