等到元素可单击不会正确超时



我在处理超时时遇到了一些问题,因为它似乎并非在所有情况下都有效。我已将超时定义如下:

wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(60))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(NoSuchElementException.class);

现在,当我想等到页面上出现元素时,我使用这段代码:

wait.until(ExpectedConditions.presenceOfElementLocated(locator));

它在大多数情况下都有效(等待元素并在 60 秒后超时),但最近我们在一些页面加载时遇到了问题(有一条消息在等待......在页面的左下角)。发生这种情况时,我意识到这段代码无法正常工作。它不会在 60 秒后超时,而是在 10 分钟后超时。

编辑:实际上,试图进一步调查我的问题,我意识到它确实来自另一行代码,该代码也包含等待:

wait.until(ExpectedConditions.elementToBeClickable(locator));

基本上,我单击重定向到另一个页面的链接,等待按钮存在,等待按钮可单击,然后单击按钮。因此,它会检测到按钮存在,但随后会等待它可单击,并且在 60 秒后不会超时。

因此,当我定义驱动程序时,我添加了以下行:

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);

在控制台中,我看到以下行: 从渲染器接收消息超时:60.000

但是如何捕获此异常?我试图用尝试/捕获来包围我的等待,但它不起作用。

try {
wait.until(ExpectedConditions.elementToBeClickable(locator));
} catch (Exception e) {
logger.info("TEST");
throw new TimeoutException("element " + locator.toString() + " not found on the page");
}

我该怎么做?谢谢。

您需要处理以下几件事:

  • 理想情况下,如果您的用例是获取元素的任何属性(例如类名innerHTML等)或在元素上调用click(),那么等到页面上存在元素不会有太大帮助。
  • 相反,根据您的用例,您需要使用visibilityOfElementTLocation()或elementToBeClickable()。
  • 您可以在以下位置找到一些详细的讨论:
    • WebDriverWait 未按预期工作
    • Java Wrapper方法,用于等待元素可用于Apache CordovaWebview驱动的应用程序
    • 硒:检查元素的存在
  • 代码行wait.until(ExpectedConditions.presenceOfElementLocated(locator))60 秒后但不超时但在10 分钟后的原因可能是由于以下原因:除了 WebDriverWait,您还配置了隐式等待,并且根据文档混淆隐式等待和显式等待可能会导致不可预测的等待时间
  • 要配置 pageLoadTimeout,您可以使用以下代码块:

    • 代码块:

      System.setProperty("webdriver.chrome.driver", "C:\Utility\BrowserDrivers\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      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");
      }catch(WebDriverException e){
      System.out.println("WebDriverException occured");
      }
      driver.quit();
      
    • 控制台输出:

      INFO: Detected dialect: W3C
      [1563377008.449][SEVERE]: Timed out receiving message from renderer: 1.999
      [1563377008.450][SEVERE]: Timed out receiving message from renderer: -0.001
      [1563377008.461][SEVERE]: Timed out receiving message from renderer: -0.012
      [1563377010.466][SEVERE]: Timed out receiving message from renderer: 1.998
      [1563377010.467][SEVERE]: Timed out receiving message from renderer: -0.001
      [1563377010.476][SEVERE]: Timed out receiving message from renderer: -0.010
      WebDriverException occured
      
  • 您可以在 pageLoadTimeout in Selenium 中找不到相关的详细讨论

最新更新