91
102

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でスクレイピング

Last updated at Posted at 2016-02-26

ちょっと前まではMechanizeとかでやってたんですが、最近のはJavascriptが動くのが前提なサイトが多いので、Capybara+Poltergeistでやることにしてます。

性能で問題が出た時だけMechanizeとかにすれば良いんじゃないかな。

PhantomJS入れる

brew install phantomjs

Gem入れる

Gemfile
gem 'nokogiri'
gem 'poltergeist'
gem 'capybara'

アクセスするところまで

User-Agentは適当に


require 'capybara/poltergeist'

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, {:js_errors => false, :timeout => 5000 })
end

session = Capybara::Session.new(:poltergeist)

session.driver.headers = {
    'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2564.97 Safari/537.36"
}
session.visit "http://www.yahoo.co.jp"

Capybara周りの使い方

ID/パスワード入力して次のページヘ

email_input = session.find('input#email')
email_input.native.send_key('mail@example.com')

password_input = session.find('input#password')
password_input.native.send_key('mypassword')

submit = session.find('#submit-button')
submit.trigger('click')

htmlを取得

html = session.html

iframeの中のHTMLを取得

iframe_html = session.evaluate_script('$("#IFrame")[0].contentWindow.document.body.innerHTML')

htmlをパースしてオブジェクト生成

doc = Nokogiri::HTML.parse(html)

Nokogiriの使い方

参考: http://d.hatena.ne.jp/otn/20090509/p1

基本的にはCSSセレクタ派なのでその使い方をメインに

cssセレクタで要素を検索

elements = doc.css('.section')

参考 http://weboook.blog22.fc2.com/blog-entry-268.html

HTMLを取得

to_html = doc.to_html
inner_html = doc.inner_html

属性

keys = doc.keys #属性名
values = doc.values #属性値
attributes = doc.attributes #ハッシュで

これくらいあればだいたいなんでもできるはず(たぶん)。

91
102
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
91
102

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?