调用click方法时元素不可见

时间:2018-08-06 13:11:27

标签: c# selenium-chromedriver selenium3

我正在尝试使用以下代码打开</li>元素:

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;
                }
            }

        }
    }

但是li.SendKeys(Keys.Enter)li.Click()都给我“测试方法SeleniumTests.SeleniumTests.TestMethod1抛出异常: OpenQA.Selenium.ElementNotVisibleException:元素不可见”

1 个答案:

答案 0 :(得分:1)

我不确定为什么要创建Iwebelement a,为什么要使用SendKeys

这是更新代码(对我有用):

 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));
}