LoginSignup
20
20

More than 5 years have passed since last update.

Splinter + PhantomJS を使って headless(GUI無し) でブラウザの挙動を制御する

Posted at

Introduction

フロントのテストやスクレイピング、あるサイトでの処理を自動化したい等、ブラウザの挙動をハックしたいケースは多々あると思います。

でも、Mechanize は JavaScript によって制御されているサイトをうまく扱えないし、Selenium の Python-binding のメソッド名は少し冗長であるように個人的には思います。

そこで、Splinter + PhantomJS ですっきりと headless でのブラウザハックを実現したいと思います。

Splinter は Selenium 同様に、ブラウザのエミュレーションより上位のレイヤーで動作していて、各種ブラウザやフレームワークに(Firefox/zope.testbrowser/PhantomJS, etc)統一的な I/F を提供します。

Splinter を I/F として PhantomJS を使ってみるというのが今回の目的です。

Installation

今回は pip で Splinter を、apt で PhantomJS を導入しました。

pip install splinter
apt-get install phanomjs

Usage

Yahoo!JAPAN の検索で猫画像の URL を収集してみようと思います。


# ブラウザの作成
from splinter import Browser
browser = Browser('phantomjs')

# Yahoo!JAPAN のサイトへ移動
browser.visit('http://www.yahoo.co.jp/')

# 検索ボックスに「猫」と入力
browser.find_by_name('p').first.fill(u'猫')

# 画像検索ボタンをクリック
browser.find_by_id('isearch').first.click()

# 猫画像をグリッドしている div 要素の取得
div = browser.find_by_id('gridlist').first

# グリッド内の img タグを取得して、src 属性を表示
for img in div.find_by_tag('img'):
    print img['src']
http://r04.isearch.c.yimg.jp/image?id=51fc1a75b99a36669725814b6e474e06
http://r03.isearch.c.yimg.jp/image?id=5def9b9478b5585581f2b3c3c767156f
http://r03.isearch.c.yimg.jp/image?id=43d55d1fe21ef4c4ceed9c1a2faa4dd3
...

無事に猫の画像を取得出来ました!!可愛いですね!!

猫画像

Tips

DOM の要素の検索に用意されているメソッドは次のとおりです。

browser.find_by_css('h1')
browser.find_by_xpath('//h1')
browser.find_by_tag('h1')
browser.find_by_name('name')
browser.find_by_id('firstheader')
browser.find_by_value('query')

リンクは次のメソッドで探せます。

browser.find_link_by_text('Link for Example.com')
browser.find_link_by_partial_text('for Example')
browser.find_link_by_href('http://example.com')
browser.find_link_by_partial_href('example')

これらのメソッドの結果はすべてリストで返ってくるので、実際の要素を取り出すには、イテレーションするか、インデックスを指定してアクセスしましょう。先頭の要素に関しては .first で取得できます。


elements = browser.find_by_tag('div')
for e in elements: e.click()
elements.first.click()

要素の属性には辞書のように __getitem__ で取得できます。


image_links = [image['src'] for image in browser.find_by_tag('img')]

References

Splinter Documentation (https://splinter.readthedocs.org/en/latest/)
PhantomJS (http://phantomjs.org/)

20
20
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
20
20