Seleniumの実行環境を構築 – Python編

SeleniumのWeb Driverを使ったテスト自動化環境を作るための手順をまとめます(個人的な覚書みたいなもんです)。
今回は言語としてはPythonです。個人的にはC#のほうがいいのですが、フリーで環境が全てそろい、比較的容易に作れるっていう観点で、Pythonを選択してみました。また、OSとしてはWindowsを想定して記載しています。# 1. 使用するアプリケーション

  • Python
    • 今回はバージョンとして「2.7.13」を使用します。32bitか64bitかは利用するOSで選択して下さい。
    • 執筆時(2017/04/27)のダウンロードファイル「python-2.7.13.amd64.msi」
  • PyCharm
    • PythonのIDEとしてPyCharmのCommunityを使用します。
    • 執筆時(2017/04/27)のダウンロードファイル「pycharm-community-2017.1.1.exe」
  • Selenium - Web Browser Automation
    • 今回はIEをクライアントとして使用するため、Downloadsから「The Internet Explorer Driver Server」をダウンロードします。32bitか64bitかは利用するOSで選択して下さい。
    • 執筆時(2017/04/27)のダウンロードファイル「IEDriverServer_Win32_3.4.0.zip」
      • ※OSは64bitなのですが、IEのDriverの64bit版だとTextboxへの入力が遅くなるという問題があるため、32bit版を利用します。
  • selenium 3.4.0 : Python Package Index
    • ページ下部にある「selenium-3.4.0.tar.gz」をダウンロードします。
    • 執筆時(2017/04/27)のダウンロードファイル「selenium-3.4.0.tar.gz」
  • Firefox

2. インストールおよび設定

  1. 「python-2.7.13.amd64.msi」を実行し、Pythonをインストールします。全てデフォルトでインストールしますので、インストール先はデフォルトの「C:\Python27\」です。
  2. OSのシステム環境変数の「Path」に「C:\Python27」を追加します。
  3. 「selenium-3.4.0.tar.gz」を解凍し、中身の「selenium」フォルダごと「C:\Python27\Lib」にコピーします。
  4. 「pycharm-community-2017.1.1.exe」を実行し、PyCharmをインストールします。
  5. Firefoxをインストールし、アドオンの「Selenium IDE」もインストールします。

3. テストプログラムの雛形作成

テストプログラムの雛形のソースをFirefoxのSelenium IDEを使って作成します。

  1. Firefoxを起動し、更にSelenium IDEの画面を表示します。
  2. Selenium IDEが起動した時点で操作の記録状態になっているので、自動化したい操作を行います。ここでは例としてGoogleにアクセスし、検索を実行する処理を記録しています。
    SeleniumIde
  3. 記録が完了したら、メニューの[ファイル]-[テストケースをエクスポート]-[Python2 / unittest / WebDriver]をクリックし、ファイルを保存します。
    SeleniumIde2

これで一旦雛形の作成は完了です。

4. テストプログラムの実行

用意したテストプログラムの雛形を元に実行してみます。

  1. PyCharmを起動し、Projectを作成します。
  2. 作成したPyCharmのProjectのフォルダに 3. でエクスポートしたファイルを置きます。更に、ダウンロードした「IEDriverServer_x64_3.4.0.zip」を解凍し、中身の「IEDriverServer.exe」もProjectフォルダに配置します。
  3. テストコードを開いて編集します。指定しているWebDriverがFirefoxになっているので、この部分をIEに書き換えます。以下に、編集後のソースを載せておきます。「self.driver = webdriver.Firefox()」の部分しか修正してません。
  4. 実行する前にIEの設定を行います。SeleinumでIEを動かす場合には、IEの設定を個別にしてあげる必要があります。設定内容については下記のページを参照して設定してください。これ設定しないと動きません。
  5. これで準備完了です。PyCharmのメニューの[Run]-[Run ‘unittests in SeleniumTest.py’ (Shift+F10)]で実行すれば、IEが立ち上がりGoogleで検索が実行されます。

[code lang=”python” title=”テストコード 編集後”]
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class SeleniumTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Ie("C:\\Users\\swk623\\Documents\\PycharmProjects\\Selenium_FHI\\IEDriverServer.exe")
self.driver.implicitly_wait(30)
self.base_url = "https://www.google.co.jp/"
self.verificationErrors = []
self.accept_next_alert = True
def test_selenium(self):
driver = self.driver
driver.get(self.base_url + "/?gfe_rd=cr&ei=UIYBWc6ENaTU8AeR5JHgCg")
driver.find_element_by_id("lst-ib").clear()
driver.find_element_by_id("lst-ib").send_keys("Selenium")
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
[/code]

5. その他

テストを実行したけど、IEが起動しない??

手順を整理する中で、動かそうとしたらIEが起動しないという問題に遭遇しました。出力されたのは以下のエラー。
[code lang=”python”]
Error
Traceback (most recent call last):
File "C:\Python27\lib\unittest\case.py", line 320, in run
self.setUp()
File "C:\Users\swk623\Documents\PycharmProjects\SeleniumTest\SeleniumTest.py", line 14, in setUp
self.driver = webdriver.Ie("C:\\Users\\21680193\\Documents\\PycharmProjects\\SeleniumTest\\IEDriverServer.exe")
File "C:\Python27\lib\selenium\webdriver\ie\webdriver.py", line 57, in __init__
desired_capabilities=capabilities)
File "C:\Python27\lib\selenium\webdriver\remote\webdriver.py", line 98, in __init__
self.start_session(desired_capabilities, browser_profile)
File "C:\Python27\lib\selenium\webdriver\remote\webdriver.py", line 185, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Python27\lib\selenium\webdriver\remote\webdriver.py", line 247, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Python27\lib\selenium\webdriver\remote\remote_connection.py", line 464, in execute
return self._request(command_info[0], url, body=data)
File "C:\Python27\lib\selenium\webdriver\remote\remote_connection.py", line 526, in _request
resp = opener.open(request, timeout=self._timeout)
File "C:\Python27\lib\urllib2.py", line 429, in open
response = self._open(req, data)
File "C:\Python27\lib\urllib2.py", line 447, in _open
‘_open’, req)
File "C:\Python27\lib\urllib2.py", line 407, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 1228, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "C:\Python27\lib\urllib2.py", line 1201, in do_open
r = h.getresponse(buffering=True)
File "C:\Python27\lib\httplib.py", line 1121, in getresponse
response.begin()
File "C:\Python27\lib\httplib.py", line 438, in begin
version, status, reason = self._read_status()
File "C:\Python27\lib\httplib.py", line 402, in _read_status
raise BadStatusLine(line)
BadStatusLine: ”
[/code]
半ば諦めかけていたのですが、、「BadStatusLine」ってどういうときに出るのか?と思いググって、「20.7. httplib — HTTP プロトコルクライアント — Python 2.7.13 ドキュメント」あたりを見て、Proxyの設定が怪しいと思い。
IEの[インターネット オプション]-[接続]-[LANの設定]で「ローカル エリア ネットワーク (LAN) の設定」ダイアログで指定していた「LAN にプロキシ サーバを使用する」のチェックを外してみたところ、動いた!!
ローカルでProxyサーバを動かしていて、そいつを経由して通常はつかっているのだけど、その辺でへんな動きをしていたのかもしれませんが、原因を追求はしてません。

コメント

Wordpress Social Share Plugin powered by Ultimatelysocial