如果加载时间过长,如何使 selenium 重新加载所需的 url

How to make selenium to reload the desired url if it takes too long loading

如果加载过程耗时过长,我希望 selenium 强制浏览器重新加载它正在加载的页面。

我从 Whosebug 得到了这段代码

new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd)
                .executeScript("return document.readyState").equals("complete"));

会等到页面完全加载,但如果超过 30 秒我希望重新加载。

我怎样才能做到这一点?

WebDriverWait 通过超时异常。将您的代码放入 try/catch 并在超时异常时重新加载页面:

try {
    new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd)
            .executeScript("return document.readyState").equals("complete"));
} catch (TimeoutException e) {
    // log a timeout
    // System.out.println("Page load timeout, refresh.");
    driver.navigate().refresh();
}

尝试_driver.Navigate().Refresh()

要重新加载网页以防加载过程花费太长时间,您可以配置 pageLoadTimeoutpageLoadTimeout 设置在抛出错误之前等待页面加载完成的时间。如果超时为负数,页面加载可以是不确定的。

示例(使用 Selenium v​​3.141.59 和 GeckoDriver v0.24.0):

  • 代码块:

    public class pageLoadTimeout 
    {
        public static void main(String[] args) 
        {
            System.setProperty("webdriver.gecko.driver", "C:\Utility\BrowserDrivers\geckodriver.exe");
            WebDriver driver=new FirefoxDriver();
            driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
            try{
              driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl");
              // do your other work here
            }catch(WebDriverException e){
              System.out.println("WebDriverException occured");
              }
            driver.quit();
        }
    }
    
  • 控制台输出:

    1565680787633   mozrunner::runner   INFO    Running command: "C:\Program Files\Mozilla Firefox\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\Users\Debanjan.B\AppData\Local\Temp\rust_mozprofile.3jw3aiyfNAiQ"
    1565680826515   Marionette  INFO    Listening on port 56499
    1565680827329   Marionette  WARN    TLS certificate errors will be ignored for this session
    Aug 13, 2019 12:50:28 PM org.openqa.selenium.remote.ProtocolHandshake createSession
    INFO: Detected dialect: W3C
    Aug 13, 2019 12:50:31 PM org.openqa.selenium.remote.ErrorCodes toStatus
    WebDriverException occured
    
  • 您可以在

  • 中找到相关讨论

You can find a detailed discussion in Do we have any generic function to check if page has completely loaded in Selenium