Search code examples
c#selenium-chromedriverselenium3

Element not visible when calling click method


I'm trying to open a </li> element with this code:

DropDownElementByText("language-dd", "Englisch");

public void DropDownElementByText(string elementId, string text)
    {
        using (var dr = new ChromeDriver {Url = "https://www.startpage.com/deu/advanced-search.html"})
        {
            dr.Manage().Window.Maximize();

            var wait = new WebDriverWait(dr, TimeSpan.FromSeconds(10));
            IWebElement languageDropDown = wait.Until(d => d.FindElement(By.XPath("//div[@id='" + elementId + "']/ul")));

            //new Actions(dr).MoveToElement(languageDropDown).Perform();

            ReadOnlyCollection<IWebElement> languages = languageDropDown.FindElements(By.TagName("li"));
            foreach (IWebElement li in languages)
            {
                IWebElement a = dr.FindElement(By.XPath("//div[@id='" + elementId + "']/ul/li/a[text()='" + text + "']"));

                if (a != null)
                {
                    new Actions(dr).MoveToElement(li).Perform();
                    //li.Click();
                    li.SendKeys(Keys.Enter);
                    break;
                }
            }

        }
    }

But li.SendKeys(Keys.Enter) or li.Click() both give me "Test method SeleniumTests.SeleniumTests.TestMethod1 threw exception: OpenQA.Selenium.ElementNotVisibleException: element not visible"


Solution

  • I am not sure why were you creating Iwebelement a and why are you using SendKeys, if click works.

    Here's the update code (which is working for me):

     var dropdown = Driver.FindElement(By.XPath("//*[@id='language-dd']"));
    var coll = Driver.FindElements(By.XPath("//*[@id='language-dd']/ul/li"));
    foreach (var item in coll)
    {
        dropdown.Click();
        item.WaitForElementToBeClickable(30);
        item.Click();
    }
    
    public static void WaitForElementToBeClickable(this IWebElement element, int timeout)
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout)).Until(ExpectedConditions.ElementToBeClickable(element));
    }