LoginSignup
16
19

More than 5 years have passed since last update.

WebdriverIO と Selenium で Node.js からスクレイピングできる環境をつくる。

Last updated at Posted at 2016-01-18

昨今、PhantomJS さえあれば何でもスクレイピングできるのか思ったら、そうでもない web サイトがあったりして、Selenium を試してみたので、OS X での手順をまとめておきます。

Selenium 環境をつくる

Selenium Standalone Server を導入

Selenium Standalone Server をダウンロードして適当なディレクトリに配置します。

cd ~/Developer/opt/selenium-server-standalone
curl -LO http://selenium-release.storage.googleapis.com/2.49/selenium-server-standalone-2.49.0.jar

今回は ~/Developer/opt/selenium-server-standalone 以下に配置する事にします。

WebDriver として ChromeDriver を導入

Selenium の標準 WebDriver は Firefox みたいですが、今回は Google Chrome を使いたいので ChromeDriver もダウンロードして PATH が通ったディレクトリに配置します。

cd ~/Developer/opt/selenium-server-standalone
curl -LO http://chromedriver.storage.googleapis.com/2.20/chromedriver_mac32.zip && unzip -d . ./chromedriver_mac32.zip && rm ./chromedriver_mac32.zip
ln -s ~/Developer/bin/chromedriver ~/Developer/bin/chromedriver

今回は ~/Developer/opt/selenium-server-standalone 以下に配置し、PATH の通った ~/Developer/bin/ 以下に chromedriver のシンボリックリングを配置します。

Node.js で Selenium を使う環境をつくる

WebdriverIO の導入

適当な作業ディレクトリを用意して WebdriverIO をインストールします。

npm install webdriverio

Node.js でスクリプトを動かす

WebdriverIO 用のスクリプト作成

WebdriverIO をインストールしたディレクトリ下で、次のテストスクリプトを作成します。

test.js
'use strict';

var webdriverio = require('webdriverio');

var client = webdriverio
.remote({ desiredCapabilities: { browserName: 'chrome' } })
.init()
.url('https://www.google.com/');

client
.getTitle()
.then(function (title) {
  console.log(title);
})
.getHTML('body')
.then(function (data) {
  console.log(data);
})
.end();

スクリプトの実行

まず Selenium Standalone Server を起動します。

cd ~/Developer/opt/selenium-server-standalone
java -jar ./selenium-server-standalone-2.49.0.jar

そして、先ほどのスクリプトを Node.js で実行します。

node ./test.js

あとは、WebdriverIO - API Docs にある API に沿ってスクリプトを書けば、スクレイピングでも何でもできそうです。

16
19
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
16
19