LoginSignup
0

More than 3 years have passed since last update.

Rubyスクレイピング-VPSでSeleniumをHeadlessに動かす。

Last updated at Posted at 2020-06-29

開発環境

ruby2.7.1
centos7

手順

①Gemを追加しよう

gem install gem install selenium-webdriver

②GoogleChromeをインストール

インストールする
yum install google-chrome-stable
バージョン確認しておく
google-chrome -version

③GoogleChromeをインストール

http://chromedriver.chromium.org/downloads からgoogle-chromeと同じバージョンのChromeDriverをダウンロードする

下記はGoogleChromeがバージョン83.0.4103.39のコマンド
wget https://chromedriver.storage.googleapis.com/index.html?path=83.0.4103.39/

展開
unzip chromedriver_linux64.zip
移動
sudo mv chromedriver ~/usr/local/bin/
権限変更
sudo chmod 755 /usr/local/bin/chromedriver

準備完了

④Seleniumをつかったサンプルコード

scraping.rb
def scraping
  url = 'https://google.com/' #開きたいURL
  options = Selenium::WebDriver::Chrome::Options.new #オプションをNew
  options.add_argument('--headless') #ヘッドレスオプション追加
  options.add_argument('--disable-gpu') #GPUを向こう
  options.add_argument('--window-size=4000,4000') #画面を最大化
  driver = Selenium::WebDriver.for :chrome, options: options #オプションを反映してdriverをNew
#お好きにスクレイピングコードを
.
.
.
.
end

--headless--disable-gpuはLinuxのためヘッドレスで処理するために追加
--window-size=4000,4000のオプションの追加は画面に表示されている部分でしかスクレイピングができないので書いてます。

linuxでGUIを表示したい場合は別途バーチャルディスプレイをインストールする必要あり

※ビットコインの自動売買ツールを制作する人に向けて(最近多いので)

SeleniumはAPIがないサイトを自動化するのに向いてます。
ビットコインの自動売買とかでしたらSeleniumは必要ないです。下記のようにBitflyerのAPIを使って作った方が良いと思います。
http://benzenetarou.hatenablog.com/entry/bitcoin/automatic_trade/1

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