LoginSignup
10
8

More than 5 years have passed since last update.

python の unittest で selenium の phantomjs webdriver を使う

Posted at

python の unittest で selenium の phantomjs webdriver を使う

  • 先に pip install selenium しておく
  • phantomjs にパス通しておく
  • useragentの指定は desired_capabilities でできるらしい
  • ついでにwebdriverの設定はクラスのデコレータに切り出してみた
  • 最後に driver.quit() しておかないとスクリーンショットが保存されなかったりする
test.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import unittest
import commands

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53"


def unittest_phantomjs_webdriver_decorator(klass):
    def __setUpClass(cls):
        (status, phantomjs_path) = commands.getstatusoutput("which phantomjs")
        if not status == 0:
            raise StandardError("phantomjs is not found!!")

        cls.driver = webdriver.PhantomJS(
            executable_path=phantomjs_path,
            service_log_path="/dev/stdout",
            desired_capabilities={
                'phantomjs.page.settings.userAgent': USER_AGENT,
            },
            # proxy通す場合
            #service_args=[
            #    '--proxy=127.0.0.1:9999',
            #    '--proxy-type=http',
            #],
        )
        cls.driver.set_window_size(1400, 1000)
        cls.driver.implicitly_wait(1)

    def __tearDownClass(cls):
        cls.driver.quit()

    klass.setUpClass = classmethod(__setUpClass)
    klass.tearDownClass = classmethod(__tearDownClass)
    return klass


@unittest_phantomjs_webdriver_decorator
class AccessTest(unittest.TestCase):

    def test_google(self):
        driver = self.driver
        url = """http://google.com"""
        driver.get(url)
        driver.save_screenshot("google.png")

    def test_amazon(self):
        driver = self.driver
        url = """http://amazon.com"""
        driver.get(url)
        driver.save_screenshot("amazon.png")

if __name__ == "__main__":
    unittest.main()
10
8
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
10
8