【问题标题】:Implicit to Explicit waits within test c# selenium在测试 c# selenium 中隐式到显式等待
【发布时间】:2018-11-29 19:31:33
【问题描述】:

我编写了一个隐式等待 5 秒的测试。我一直在寻找在我的代码中引入显式等待的方法,这样执行就不会花费那么长时间。

我已经看到有许多不同的方法可以将显式方式引入代码。我将如何进行如下操作,但我不确定对我来说正确的方法是什么

     WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.Id("someDynamicElement")));
}

/

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver webDriver = new ChromeDriver();
            webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
            webDriver.Manage().Window.Maximize();
            webDriver.FindElement(By.XPath(".//button[@data-testid='country-selector-btn']")).Click();


            webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            IWebElement country = webDriver.FindElement(By.Id("country"));
            SelectElementFromDropDown(country, "India");
            webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);



            IWebElement currency = webDriver.FindElement(By.Id("currency"));
            SelectElementFromDropDown(currency, "$ USD");
            webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);




            webDriver.FindElement(By.XPath(".//button[@data-testid='save-country-button']")).Click();

            webDriver.Quit();

        }

        private static void SelectElementFromDropDown(IWebElement ele, string text)
        {
            SelectElement select = new SelectElement(ele);
            select.SelectByText(text);
        }
    }

}

【问题讨论】:

    标签: c# selenium selenium-webdriver


    【解决方案1】:

    您误解了ImplicitWait 的工作原理。您一直调用它,就像您期望它每次等待 5 秒一样。 ImplicitWait 超时在驱动程序的生命周期内设置一次。如果您要删除设置超时的所有实例(第一个除外),您的脚本将完全相同。

    在我进入显式等待之前快速说明... Selenium 文档state not to mix them

    警告:不要混合隐式和显式等待。这样做可能会导致无法预料的等待时间。

    对于显式等待,您将等待特定的东西...一个元素出现、可见、可点击等。您可以查看WebDriverWaitExpectedConditions 的文档更多细节。

    一个简单的例子

    // create a new instance of WebDriverWait that can be reused
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
    IWebElement button = wait.Until(ExpectedConditions.ElementExists(By.Id("someId"));
    // do something with button
    

    ExpectedConditions 中已有许多不同的条件可供您等待,因此请确保您熟悉它们。一般来说,你很少需要那里没有提供的东西,所以在编写自定义条件之前检查一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2012-05-11
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多