49
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Seleniumでページ読み込みのリトライを試す

Last updated at Posted at 2018-02-06

概要

Seleniumでページの読み込みが終わらない現象が時々発生し、エラーとなってテスト実行が不安定となるため、リトライを試してみる。

ページの読み込み最大待ち時間の指定する

とりあえず、読み込みを待つ最大の時間をセットして、
ページ読み込みが終わらない場合は終了させる。

from selenium import webdriver
 
driver = webdriver.Chrome("D:\chromedriver")
driver.set_page_load_timeout(10)  # 10秒

try:
    driver.get("https://google.co.jp/")
    print("The page was loaded in time!")
except:
    print("time out!")

リトライ処理を実装する

ページの読み込みに失敗したら、リトライするように実装してみる。

#!/usr/bin/python

import unittest, time
from selenium.common.exceptions import TimeoutException

class TestHoge(unittest.TestCase):

    RETRIES = 3
    TIMEOUT = 10

    """初期化"""
    def setUp(self):
        self.browser = Browser()

    """テスト終了"""
    def tearDown(self):
        self.browser.quitBrowser()

    """PCサイト"""
    def testPcSite(self):
        # ブラウザ起動
        self.browser.openChrome()
        driver = self.browser.driver
        driver.maximize_window()  # 最大化
        driver.implicitly_wait(2) # 暗黙の待機(2秒)

        # ページの読み込み待ち時間(10秒)
        driver.set_page_load_timeout(self.TIMEOUT)

        i = 0
        while i < self.RETRIES:
            try:
                driver.get("https://google.co.jp/")
                time.sleep(5)

            except TimeoutException:
                i = i + 1
                print("Timeout, Retrying... (%(i)s/%(max)s)" % {'i': i, 'max': self.RETRIES})
                continue

            else:
                return True

        msg = "Page was not loaded in time(%(second)s sec)." % {'second': self.TIMEOUT}
        raise TimeoutException(msg)


##### MAIN #####
if __name__ == "__main__":
    unittest.main()

参考サイト

49
37
1

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
49
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?