首页 > 解决方案 > 获得时间异常后,我将如何重新启动 Web 驱动程序并继续运行脚本?

问题描述

我通过以下方式为 driver.get() 设置了超时

self.driver.set_page_load_timeout(30)

then Tried below code 

try :
    driver.get(url)
    print("URL successfully Accessed")
except TimeoutException as e:
    print("Page load Timeout Occured. Quiting !!!")
    pass

问题是这里有 10 个链接正在运行,如果一个链接发生 TimeoutException,则下一个链接未由 driver.get() 打开。我有以下方法可以关闭驱动程序并重新启动。

except TimeoutException as e:
        print("Page load Timeout Occured. Quiting !!!")
        driver.close()
        driver.get("https://www.google.com/")
        pass

但是,不幸的是结果是一样的。如何重新启动驱动程序并继续打开脚本?

标签: pythonpython-3.xseleniumselenium-webdriver

解决方案


我主要用Java编写代码。所以片段在下面的Java中。当您遇到 TimeoutException 时,您将关闭驱动程序。由于只打开了一个浏览器,驱动程序退出(会话结束)。因此,您需要创建一个新的 ChromerDriver 实例。您可以通过检查会话异常来做到这一点。

        WebDriver driver = new ChromeDriver();
        for (int i = 1; i < 10; i++) {
            try {
                System.out.println(("Getting Page " + i));
                driver.get("http://www.google.com");
                driver.manage().window().maximize();
                if(i==2) {
                    throw new org.openqa.selenium.TimeoutException();
                }
            }

            catch (org.openqa.selenium.TimeoutException e) {
                System.out.println(("Page load Timeout Occured. Quiting !!!"));
                driver.close();
            }
            
            catch (org.openqa.selenium.NoSuchSessionException e) {
                driver = new ChromeDriver();
            }
        }

推荐阅读