Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

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()

参考サイト

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした