![](/img/trans.png)
[英]How to initialize SelectElements while using PageFactory / FindsBy in Selenium C#?
[英]Selenium c# Find element exist on a page using Pagefactory
我正在將硒腳本遷移到PageFactory,並且目前一直在查找頁面上是否存在元素
我當前的實現是
public bool IsElementExist(string element)
{
try
{
Driver.FindElement(By.XPath(element));
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
我的頁面上的購物籃中有多個項目,如果我需要刪除所有/某些項目。 每次刪除頁面時,頁面都會刷新,但是Pagefactory FindsBy不會刷新,並且會保留第一個值。 請協助。
當有多個元素與給定的定位器匹配時,findElement()方法僅選擇第一個並返回相應的WebElement。 有時這可能會造成混淆,因為您可能會無意間與其他元素進行交互。
下面是一個更好的函數實現方式(Java中的示例,但在C#中的工作方式類似):
public Boolean objectExists(By by) {
int numberOfMatches = driver.findElements(by).size();
if(numberOfMatches == 1) {
return true;
}
else {
// 0 matches OR more than 1 match
return false;
}
}
不知道這是否與您的問題直接相關,但是值得一試。
在下面,我正在執行等待,但是它提供了一個示例,該示例說明如何傳遞IWebElement來查找對象並執行操作。 您提供的方法將期望您以字符串形式提供XPath,而不是頁面上已經標識的元素的名稱。
// Wait Until Object is Clickable
public static void WaitUntilClickable(IWebElement elementLocator, int timeout)
{
try
{
WebDriverWait waitForElement = new WebDriverWait(DriverUtil.driver, TimeSpan.FromSeconds(10));
waitForElement.Until(ExpectedConditions.ElementToBeClickable(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
這位於我從MyPageFunctionality.cs調用的BaseUtil.cs中,如下所示:
BaseUtil.WaitUntilClickable(btnLogin, 10);
這行得通嗎?
//call the method and pass the xpath. You can also create css, id etc.
page.WaitForElementNoLongerDisplayed_byXpath("//div[contains(@class, 'my-error-message')]");
public static void WaitForElementNoLongerDisplayed_byXpath(string elementXpath)
{
try
{
_wait.Until(driver => driver.FindElements(By.XPath(elementXpath)).Count == 0);
}
catch (Exception)
{
LogFunctions.WriteError("Element is still displayed and should not be");
TakeScreenshot("elementStillShown");
throw;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.