Explicit waits in Selenium C# doesn't work . What is wrong?

不问归期 提交于 2019-12-04 14:35:27

I am coding with Selenium for 6+ months and I had the same problem as yours. I have created this extension method and it works for me every time.

What the code does is: During 20 seconds, it checks each 500ms, whether or not the element is present on the page. If after 20 seconds, it's not found, it will throw an exception. This will help you make a dynamic wait.

  public static class SeleniumExtensionMethods {
      public static WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
      public static void SafeClick(this IWebElement webElement) {
          try {
              wait.Until(ExpectedConditions.ElementToBeClickable(webElement)).Click();
          } catch (TargetInvocationException ex) {
              Console.WriteLine(ex.InnerException);
          }

      }

and then replace this code of yours:

driver.FindElement(By.XPath("//span/ul/li/span/a")).Click();

with:

IWebElement x = driver.FindElement(By.XPath("//span/ul/li/span/a"));
x.SafeClick();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!