我有一個頁面,在某些時候,它不會在 selenium 中加載。如果我在硒打開的頁面上單擊“重新加載”按鈕,有時頁面會加載。此頁面是一個遺留系統,我們無法更改它。
然后我需要創建一個條件,如下所示:
如果 Id:xxx 可見
- 連續執行
如果沒有:
- driver.navigate().refresh();
我正在使用 Selenium Java。
uj5u.com熱心網友回復:
我建議實作一個 custom ExpectedCondition,例如:
import org.openqa.selenium.support.ui.ExpectedCondition
public static ExpectedCondition<Boolean> elementToBeVisibleWithRefreshPage(By element, int waitAfterPageRefreshSec) {
return new ExpectedCondition<Boolean>() {
private boolean isLoaded = false;
@Override
public Boolean apply(WebDriver driver) {
List elements = driver.findElements(element);
if(!elements.isEmpty()) {
isLoaded = elements.get(0).isDisplayed();
}
if(!isLoaded) {
driver.navigate().refresh();
// some sleep after page refresh
Thread.sleep(waitAfterPageRefreshSec * 1000);
}
return isLoaded;
}
};
}
用法:
By element = By.id("xxx");
new WebDriverWait(driver, Duration.ofSeconds(30)).until(elementToBeVisibleWithRefreshPage(element, 10));
這將等待 30 秒,直到元素可見,如果元素不可見,它將以 10 秒的暫停重繪 頁面。
潛在的睡眠可能會被其他一些 WebDriver 等待所取代,但這也應該有效。
uj5u.com熱心網友回復:
最簡單的方法是將代碼塊包裝在一個塊中以持續執行,從而為visibilityOfElementLocated()try-catch{}引入WebDriverWait ,如下所示:
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
try
{
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(20)).until(ExpectedConditions.visibilityOfElementLocated(By.id("elementID")));
// other lines of code of continius execution
}
catch(TimeoutException e)
{
driver.navigate().refresh();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/424661.html
