4 回答

TA貢獻1725條經驗 獲得超8個贊
幾個問題:
存在意味著它存在于 DOM 中,但不一定是可見的、可點擊的等。如果您希望元素可見,則等待可見。
您正在使用
*Elements*
which 是復數,它將等待定位器找到的所有元素,而不僅僅是您專門尋找的元素。如果您沒有唯一的定位器,這可能會導致混亂的失敗等。如果你只想要單數,我會避免使用復數。您應該仔細閱讀文檔。有一種
ExpectedConditions
方法可以完全滿足您的需求。
公共靜態 ExpectedCondition visibilityOf(WebElement 元素)
您的代碼應該看起來更像
public static void waitForElementToAppearInDOM(WebElement element, int timer) {
try {
new WebDriverWait(getDriver(), timer).until(ExpectedConditions.visibilityOf(element));
} catch(Exception e) {
// don't leave an empty catch, do something with it or don't catch it.
}
}

TA貢獻1818條經驗 獲得超11個贊
在public static ExpectedCondition visibilityOf(WebElement element): 檢查已知存在于頁面 DOM 上的元素是否可見之前,您是非常正確的。可見性意味著元素不僅被顯示,而且具有大于 0 的高度和寬度。上述現有方法檢查元素是否可見并且存在于 DOM 中,但不僅存在于 DOM 中。
為簡單起見,我將重新表述這個 ExpectedCondition,因為期望檢查已知存在于頁面 DOM 中的元素是可見的。
粗略的兩種期望presenceOfElementLocated()
,visibilityOf()
它們之間有很多差異。
回到您的主要問題,使用 WebElement作為參數來等待特定的 WebElement 出現是不可能的。原因很簡單,WebElement在 DOM 中還沒有被識別,只有在期望或成功后才會被識別。presenceOfElementLocated
findElement()
JavaDocs中與元素的存在相關的ExpectedCondition列表突然支持了這個概念,如下所示:
presenceOfNestedElementLocatedBy(By locator, By childLocator)
presenceOfNestedElementLocatedBy(WebElement element, By childLocator)
presenceOfNestedElementsLocatedBy(By parent, By childLocator)
總而言之,您不能將WebElement作為參數作為期望傳遞,presenceOfElementLocated()
因為WebElement尚未被識別。但是一旦元素被識別,findElement()
或者presenceOfElementLocated()
這個WebElement可以被傳遞一個參數。
總結一下:
presenceOfElementLocated(By locator)
:這個期望是為了檢查一個元素是否存在于頁面的 DOM 中。這并不一定意味著元素是可見的。visibilityOf(WebElement element)
: 這個期望是為了檢查一個已知存在于頁面 DOM 上的元素是否可見??梢娦砸馕吨夭粌H被顯示,而且具有大于0的高度和寬度。

TA貢獻1831條經驗 獲得超9個贊
此方法“visibilityOfElementLocated”使用方式:
示例://等待元素可見
WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='text3']")));

TA貢獻1895條經驗 獲得超7個贊
如何使用WebElement作為參數檢查存在。
public boolean isElementPresent(WebElement element) {
if (element != null) {
try {
//this line checks the visibility but it's not returned.
//It's to perform any operation on the WebElement
element.isDisplayed();
return true;
} catch (NoSuchElementException e) {
return false;
}
} else return false;
}
添加回答
舉報