如何使用硒元素等待,检查,点击而不再次找到元素



我是Selenium的新手,以前使用Telerik免费测试框架。问题是我无法理解,如何使用已经与[FindsBy]识别的元素等待,检查并单击。

,

    [FindsBySequence]
    [FindsBy(How = How.Id, Using = "container-dimpanel")]
    [FindsBy(How = How.CssSelector , Using = ".btn.btn-primary.pull-right")]
    public IWebElement UpdateButton { get; set; }
    internal void ClickUpdateButton(TimeSpan timeout)
    {
        new WebDriverWait(_driver, timeout).
            Until(ExpectedConditions.ElementIsVisible(By.CssSelector(id));
        UpdateButton.Click();
    }

我希望我的代码等待更新按钮可见,然后单击它。但我只想传递UpdateButton元素而不是使用By选择器。

  • 不确定是否UpdateButton。Enabled将等待,直到它可见。

有一个接受WebElement的可见性的预期条件:https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html visibilityOf-org.openqa.selenium.WebElement——

Until还返回正在等待的元素,因此您可以将其组合成一行:

internal void ClickUpdateButton(TimeSpan timeout)
{
    WebDriverWait wait = new WebDriverWait(_driver, timeout);
    wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click();
}

然而,在我的框架中,我通常会添加一个辅助函数来做这件事,因为它被使用得太多了。你也可以用wait until clickable等来做类似的事情,并让方法接受WebElement或By:

public WebElement waitThenClick(WebElement element) 
{
    WebDriverWait wait = new WebDriverWait(_driver, timeout);
    return wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click();
}

c#客户端没有一个内置的条件来检查被代理的WebElement的可见性

此外,预期条件ExpectedConditions.ElementIsVisible检查元素是否显示,但不检查元素是否从用户角度可见。

所以最快和最可靠的方法是在服务员中重试点击,直到成功:

Click(UpdateButton, 5);
static void Click(IWebElement element, int timeout = 5) {
    var wait = new DefaultWait<IWebElement>(element);
    wait.IgnoreExceptionTypes(typeof(WebDriverException));
    wait.PollingInterval = TimeSpan.FromMilliseconds(10);
    wait.Timeout = TimeSpan.FromSeconds(timeout);
    wait.Until<bool>(drv => {
        element.Click();
        return true;
    });
}

使用我编写的这个函数来测试元素,您可以只传递名称。它将返回一个bool值,您可以使用循环等待元素出现。

static public bool verify(string elementName)
{
    try
    {
        bool isElementDisplayed = driver.FindElement(By.XPath(elementName)).Displayed;
        return true;
    }
    catch
    {
        return false;
    }
    return false;
}

最新更新