てけとーぶろぐ。

ソフトウェアの開発と、お絵かきと、雑記と。

Selenium+PythonでChromeの自動操作

Webアプリのテストのときや、Web上のデータ収集のときなど
Webブラウザーを自作プログラムから操作できると便利なことがある。

というわけでSelenium+PythonChromeを自動操作してみる。

今回は Windows, Python 2.7 という組み合わせで行ったけど
Python 3.x でも同様だと思う。

Pythonのインストール

https://www.python.org/の「Download」から
python-2.7.13.msi」をダウンロードしてインストールする。

PythonSeleniumのインストール

「C:\Python27」「C:\Python27\Scripts」にパスを通した状態で
コマンドプロンプトから以下を実行する。

pip install selenium

Chrome用ドライバーのインストール

https://sites.google.com/a/chromium.org/chromedriver/downloads
の「Latest Release: ChromeDriver 2.29」のリンクから
「chromedriver_win32.zip」をダウンロード、展開して
中の「chromedriver.exe」を適当な場所に置く。

操作用Pythonスクリプトの作成

例えば「main.py」として以下のように作成する。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

WAIT_SECOND = 30

if __name__ == '__main__':

    driver = webdriver.Chrome()  
    driver.maximize_window()    
    driver.get('https://google.co.jp')
    
    # 検索キーワードとエンターキーを入力
    t=driver.find_element_by_id('lst-ib')
    t.send_keys(u'てけとーぶろぐ\n')

    # 要素の表示待ち
    WebDriverWait(driver, WAIT_SECOND).until(
        EC.visibility_of_element_located((By.CLASS_NAME, '_Rm')))

    # リンクをクリック
    b=driver.find_element_by_xpath('//*[@id="rso"]/div/div/div[1]/div/div/h3/a')
    b.click()

    # 要素の表示待ち
    WebDriverWait(driver, WAIT_SECOND).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'entry-title-link')))

    # ソースの書き出し
    file_name = 'test.html'
    with codecs.open(file_name, 'a', 'utf_8') as f:
        f.write(driver.page_source)

    driver.close()

操作用Pythonスクリプトの実行

「chromedriver.exe」にパスを通した状態で
作成した操作用Pythonスクリプトを実行する。

python main.py

ポイント

要素情報の確認方法

スクリプトでWebサイト上の要素を指定するのに
要素のXPathなどが必要だがこの確認には
Webブラウザーの機能を使うのが楽。
ChromeだとF12キーでデベロッパーツールを表示して
Shift+Ctrl+C を押してから要素をマウスクリック。
HTML上でハイライトされた行を右クリックして
Copy → Copy XPath とか。

確実なロード待ち方法

読み込み待ちには上記の例のように表示を待つのが確実。
サイトによっては要素を非表示状態でロードした後
動的に表示状態に切り替えたりするので。

その他の要素指定方法

要素の指定の仕方はXPath以外にも幾つかある。
ドキュメントをどうぞ。
http://selenium-python.readthedocs.io/locating-elements.html