![](/img/trans.png)
[英]How to wait for either of the two elements in the page using selenium in C#
[英]How to wait for one of multiple elements to be displayed first using Selenium?
我對 Selenium 很陌生,所以我正在尋找有關如何實現這一目標的一些見解。
本質上,我希望我的驅動程序等待多個元素之一可見。 這是因為網站在使用自動化時可能會產生混合結果,所以我想將其視為“錯誤處理”(如果有道理)。
基本上,如果元素 a 首先可見,請執行此操作。 但是,如果元素 b 首先可見,請執行此操作。
我如何能夠使用 C# 的 Selenium webdriver 實現這一點? 我讀到通過使用“|”組合元素的 XPath 值工作,但是當我用我的應用程序嘗試它時,我沒有運氣。
任何答案都非常感謝! 先感謝您!
對我來說,這有點困難,因為您的元素可以在一瞬間彼此顯示。 想知道你能不能把它放在一個箱子里,拿到的時候打破?
所以我在想的是看看元素是否首先出現。
public static bool IsElementPresent_byXpath(string xpath)
{
bool result;
try { result = Driver.FindElement(By.XPath(xpath)).Displayed; }
catch (NoSuchElementException) { return false; }
catch (StaleElementReferenceException) { return false; }
return result;
}
因此,如果您這樣做,那么您可以編寫如下所示的內容,但我擔心的是,如果頁面未更改,則可能會調用 ele1、ele2 和 ele3。 所以這個代碼需要修改。
bool ele1 = Browser.IsElementPresent_byXpath("//[@id='1']");
bool ele2 = Browser.IsElementPresent_byXpath("//[@id='2']");
bool ele3 = Browser.IsElementPresent_byXpath("//[@id='3']");
if (ele1)
{
//do this
}
else if (ele2 || ele1 == false)
{
//do this
}
else if (ele3 || ele1 == false || ele2 == false)
{
//do this
}
我會選擇Wait.Until ,這樣我就可以將等待的好處與事件的設置超時結合起來,並返回匹配的定位器,這樣我就可以將我的邏輯基於結果。
這是 java 代碼,但 C# 有等價物。
假設我正在等待firstBy
、 secondBy
或thirdBy
:
By locatorOfElementThatIsPresent = new WebDriverWait(webDriver, timeoutInSeconds).<By>until(driver -> {
// findElements does not throw when element not found, so I skip try-catch
if (driver.findElements(firstBy).size() > 0) return firstBy;
if (driver.findElements(secondBy).size() > 0) return secondBy;
if (driver.findElemetns(thirdBy).size() > 0) return thirdBy;
return null; // neither found, so the method will be retried until timeout
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.