LoginSignup
22

More than 5 years have passed since last update.

MacでRuby×Seleniumを使って自動ブラウジング

Last updated at Posted at 2017-03-01

Seleniumって何?

Selenium公式サイト
Seleniumは、ブラウザ操作を自動でやってくれるものです。本来は、WebUIのテストツールとして使うもの(らしい...)

Seleniumを使うために必要な準備

Seleniumを使うために必要な準備は主に2つ!

  1. Selenium本体
  2. 使用するブラウザのドライバ

環境は「Mac」、言語は「Ruby」,ブラウザは「Chrome」の場合は以下の手順。

Selenium本体のインストール

Rubyが入っていればgemで一発です。

sudo gem install selenium-webdriver

※ Rubyのバージョンが古いと、うまくインストールできないことがあるようです。。(参考先

各種ブラウザのドライバインストール

こちらもHomebrewでイッパツです。
brew install chromedriver

実行してみる

以下のselenium_test.rbで実行できたらOK!

selenium_test.rb
# -*- coding: utf-8 -*-
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :chrome #ドライバ選択
driver.navigate.to "http://www.yahoo.co.jp/" #移動サイト指定
puts driver.title #タイトルを出力

# meta descriptionを取ってくる場合
element = driver.find_element(:name, 'description') #セレクタ指定
puts element.attribute('content') #出力

driver.quit #ブラウザを閉じる

実行するとこんな感じ↓

$ ruby selenium_test.rb                                                                               
Yahoo! JAPAN
日本最大級のポータルサイト。検索、オークション、ニュース、天気、スポーツ、メール、ショッピングなど多数のサービスを展開。あなたの生活をより豊かにする「課題解決エンジン」を目指していきます。

これだけで簡単なクローリングならできそう。nokogiriも組み合わせて使うとかなり便利!

お世話になったサイト

WebのUIテスト自動化 - Seleniumを使ってみる
Macの初期Rubyは罠かよ・・・
RubyでSeleniumを使ってスクレイピング
Webブラウザの自動操作 (Selenium with Rubyの実例集)

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
22