LoginSignup
60
60

More than 5 years have passed since last update.

Linux CUI環境でruby + selenium-webdriver

Posted at

概要

javascript使って無いサイトほとんどないと思われるので、
seleniumをつかって解析するのが一番いいと思った。

検証環境

CentOS release 6.3

rubyバージョン
#  ruby --version
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]

Xvfb(仮想フレームバッファ)の準備

インストール
# yum -y install xorg-x11-server-Xvfb
# yum -y install firefox
~/.bash_profile
export DISPLAY=:1
起動
Xvfb :1 -screen 0 1024x768x24

FireFoxの準備

インストール
# yum -y install firefox

selenium-webdriverの準備

インストール
# gem install selenium-webdriver

nokogiriの準備

インストール
# gem install nokogiri

使い方のお勉強

ためしに「ワールドカップ」で検索した結果のURLを一覧でだしてみる。

test.rb
# coding: utf-8
require 'rubygems'
require 'open-uri'
require 'selenium-webdriver'
require 'nokogiri'
require 'uri'

# 検索条件設定
search_word = "ワールドカップ"

# selenium設定
driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://google.com"

# 検索結果取得
begin
  element = driver.find_element(:name, 'q')
  element.send_keys search_word
  element.submit
  #ここでスリープしないと結果がうまくとれなかった。
  sleep 5
rescue
  #なんか失敗したらとりあえずfirefox修了
  driver.quit
end

# 解析
html = driver.page_source
kaiseki_html = Nokogiri::HTML(html)
ranking_data =  kaiseki_html.css("div.rc").css("h3")

ranking_data.each do |site|
  pp site.css("a").attribute("href").value
end


driver.quit
実行
# ruby test.rb
"http://brazil2014.yahoo.co.jp/schedule/list"
"http://www.asahi.com/worldcup/schedule/"
"http://ja.wikipedia.org/wiki/FIFA%E3%83%AF%E3%83%BC%E3%83%AB%E3%83%89%E3%82%AB%E3%83%83%E3%83%97"
"http://www.tsp21.com/sports/soccer/wc2014/"
"http://members.jcom.home.ne.jp/wcup/"
"http://blog.livedoor.jp/kaikaihanno/archives/35456376.html"
"http://samuraiblue.jp/"
"http://www.soccer-king.jp/news/wc"
"http://matome.naver.jp/topic/1LvDt"
"http://jp.uefa.com/news/newsid=2033214.html"
60
60
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
60
60