0

我正在将我的 selenium 脚本迁移到 PageFactory 并且目前坚持查找页面上是否存在元素

我目前的实现是

public bool IsElementExist(string element)
        {
            try
            {
                Driver.FindElement(By.XPath(element));
                return true;
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

我的页面的篮子上有多个项目,如果我需要删除所有/部分项目。每次我删除页面都会刷新,但 Pagefactory FindsBy 不会刷新并保留第一个值。请提供任何帮助。

4

3 回答 3

0

这行得通吗?

  //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;
        }
    }
于 2018-01-21T03:20:09.407 回答
0

下面我正在执行等待,但它提供了一个示例,说明如何传递 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);
于 2018-01-19T15:28:36.067 回答
0

当您有多个与给定定位器匹配的元素时,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;   
        }
    }

不确定这是否与您的问题直接相关,但值得一试。

于 2017-12-01T16:23:27.863 回答