Click() 在 Selenium 中的行为不一致

本文关键字:不一致 Selenium Click | 更新日期: 2023-09-27 18:35:23

我正在研究产品自动化(Web CMS),其中element.Click()显示了不一致的行为。基本上我们正在使用,

Selenium + Nunit GUI(单元测试框架) - 在特定环境中

从本地运行测试用例Selenium + Asp.net Web应用程序 - 多个用户可以在不同的环境中运行测试用例这里的环境我指的是不同的级别(开发,SIT,QA,生产)。

我的担忧在我的一个测试用例中,我想单击一个按钮。为此,我尝试了几段代码。但所有这些都是不一致的行为。在这里不一致,我的意思是,我为单击按钮编写的代码仅在我的本地或服务器中工作,反之亦然。

第一次尝试:- 我尝试了所有元素定位器的

IWebElement element = driver.FindElement(By.Id("element id goes here"))
Working fine at my local, but not in server

结果 - 失败

第二次尝试:-

driver.FindElement(By.XPath("Element XPath goes here")).SendKeys(Keys.Enter);

在服务器上工作正常,但在本地工作不正常结果 - 失败

第三次尝试:-

IWebElement element = driver.findElement(By.id("something"));
    IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
                        executor.ExecuteScript("arguments[0].click()", element);

在(本地和服务器)中都不起作用结果 - 失败

最后,我尝试等待元素可见并执行操作

第四次尝试:-

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
                return wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("element xpath goes here")));


在 Web 驱动程序等待对该元素执行操作后(element.click()) 在本地工作正常,但在服务器中工作不正常结果 - 失败

我正在寻找一种解决方案,其中单击按钮不应该是不一致的行为。基本上它应该在(本地和服务器)中都能正常工作。您的帮助将不胜感激。提前
致谢仅供参考 - 我正在 Mozilla Firefox 浏览器 38.5.2 中进行测试

Click() 在 Selenium 中的行为不一致

我在Win7本地使用C#中的Selenium,并使用Firefox浏览器在Win10和MacOS上远程使用Selenium,并且还注意到Firefox有时需要对IWebElement.Click()进行特殊处理。所以我给自己写了一个扩展方法,无论通过什么定位器找到元素,它对我来说都很好用:

public static void Click(this IWebElement element, TestTarget target)
{
    if (target.IsFirefox)
    {
        var actions = new Actions(target.Driver);
        actions.MoveToElement(element);
        // special workaround for the FirefoxDriver
        // otherwise sometimes Exception: "Cannot press more then one button or an already pressed button"
        target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
        // temporarily disable implicit wait
        actions.Release().Build().Perform();
        target.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(MyDefaultTimeoutInSeconds));
        Thread.Sleep(500);
        actions.MoveToElement(element);
        actions.Click().Build().Perform();
    }
    else
    {
        element.Click();
    }
}

如果你想让你的测试用例有更稳定的行为,我建议使用ChromeDriver。它根本不需要任何特殊处理,而且也比FirefoxDriver快得多。