近年ますますリッチになっていくWebコンテンツ、たいていのことは単純なスクレイピングでできるけど、Javascriptやら何やらを駆使したサイトは扱いづらい。
ので、いつかはブラウザ自動化を試してみたいなあと思っていた、が調べるのが面倒でChromeの拡張を作ったりしてお茶を濁していたけど、そろそろちゃんと使ってみよう。
ということでSeleniumを使ってみる。まずは動かすとこまで、
ダウンロード
Perl用のbindingがあればよかったのだけど、公式のものは無さそう。
サードパーティーでもいいんだろうけど、せっかくなので公式のものを使おう。この中ならPythonかな・・・。使ったことないけど。
WebDriver
Selenium自体は各言語からWebDriverを動かすためのライブラリ群(だと思う、WebDriverも含めてSeleniumなのかな)ので、それぞれのブラウザに対応したWebdriverというものをダウンロードしてくる。
上のSeleniumのサイトにリンクが紹介されているので適当にダウンロードして、パスの通ったディレクトリに保存する。
パスが通ってなくても、プログラム上でパスを指定できるっぽい。
インストール
準備がそろったのでSeleniumのライブラリーをインストールしよう。
If you have pip on your system, you can simply install or upgrade the Python bindings::
pip install -U selenium
Alternately, you can download the source distribution from PyPI(e.g. selenium-3.6.0.tar.gz), unarchive it, and run::
python setup.py install
pipとは。よく分からないからパッケージをダウンロードしてsetyp.pyを実行するヤツにしよう。
$ which python /usr/bin/python -> python2.7.exe $ which python3 /usr/bin/python3 -> python3.6m.exe $ ln -sf /usr/bin/python3.6m.exe /usr/bin/python
よく分からんがCygwinだとpythonはバージョン2にリンクされているようなので、バージョン3の方にリンクさせておく。
$ python setup.py Traceback (most recent call last): File "setup.py", line 22, in <module> from setuptools import setup ModuleNotFoundError: No module named 'setuptools'
setuptoolsって何やねん。面倒くさいなあ・・・。
- Python パッケージ管理技術まとめ (pip, setuptools, easy_install, etc)
- wheelのありがたさとAnacondaへの要望 - YAMAGUCHI::weblog
何かくっそややこしいな。心が折れてきた。
要するに現在はpipを使ってパッケージ管理をするのが主流で、pipはsetuptoolsを使ったツールということか。
PerlでいうとcpanmとCPANモジュールみたいなものかな?知らんけど。
ちらのうら - Cygwin上でpipとsetuptoolsをインストールする方法
なるほど。
Cygwinにpython3-pipとpython3-setuptoolsがあったのでインストールする。
binutils、libuuid-develは元々インストールしてあった。
$ pip3 install -U selenium Collecting selenium Downloading selenium-3.6.0-py2.py3-none-any.whl (924kB) 100% |################################| 931kB 585kB/s Installing collected packages: selenium Successfully installed selenium-3.6.0
なるほど、あっさりできた。えらい遠回りしたけど。。
テスト
from selenium import webdriver browser = webdriver.Firefox() browser.get('http://seleniumhq.org/')
おおー動いた。
import time from selenium import webdriver driver = webdriver.Chrome() # Optional argument, if not specified will search path. driver.get('http://www.google.com/xhtml'); time.sleep(5) # Let the user actually see something! search_box = driver.find_element_by_name('q') search_box.send_keys('ChromeDriver') search_box.submit() time.sleep(5) # Let the user actually see something! driver.quit()
Chromeのdriverをダウンロードして試してみたが、こちらも動いた。しゅごい。