C# Selenium:查找HTML5列表元素

C# Selenium:查找HTML5列表元素,c#,asp.net,selenium,selenium-webdriver,gui-testing,C#,Asp.net,Selenium,Selenium Webdriver,Gui Testing,从下面的html(它是下拉菜单的一部分)中,我需要找到元素“Hello World”并单击链接 <li data-name="Tools Menu"> <a href="javascript:void(0);">Tools</a> <ul> <li data-name="Test Menu"><a href="/Menu/Index">Test</a> </l

从下面的html(它是下拉菜单的一部分)中,我需要找到元素“Hello World”并单击链接

<li data-name="Tools Menu"> <a href="javascript:void(0);">Tools</a>
    <ul>
          <li data-name="Test Menu"><a href="/Menu/Index">Test</a>
          </li>
          <li data-name="Hello World"><a href="/HelloWorld/Hello">Hello World</a>
          </li>
    </ul>
</li>
但是,它失败了,但有以下例外:

OpenQA.Selenium.ElementNotVisibleException : Cannot click on element

我不确定,但您是否可能单击了错误的元素

<li data-name="Hello World">
    <a href="/HelloWorld/Hello">Hello World</a>
</li>

[data-name=\"Hello World\"]
  • [数据名称=\“Hello World\”]
    因此,您单击li标记而不是a标记,因为您正在搜索名为“data name”的属性

    也许这就是问题所在


    祝你好运

    这里的问题是,你的代码处理速度比页面呈现速度快,这是在处理页面中的JS或下拉菜单时经常发生的事情。我建议使用以下方法代替driver.FindElement方法:

        public static IWebElement WaitForElementPresent(this IWebDriver driver, By by)
        {
            try
            {
                return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(x => x.FindElement(by));
            }
            catch (WebDriverTimeoutException exception)
            {
                throw new AssertionException(string.Format("Element {0} was not found. Page source: {1}{2}",
                                                           by,
                                                           Environment.NewLine,
                                                           driver.PageSource),
                                                           exception);
            }
        }
    

    在处理Click()方法之前,它基本上会等待元素可见。

    线索可能在
    ElementNotVisibleException
    exception中-您绝对确定元素可见吗?也许可以让Selenium截图进行双重检查?单击“工具”菜单时,会出现一个下拉菜单,并显示“我的元素”。当我做“查看页面源代码”时,我确实看到了上面的代码
        public static IWebElement WaitForElementPresent(this IWebDriver driver, By by)
        {
            try
            {
                return new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(x => x.FindElement(by));
            }
            catch (WebDriverTimeoutException exception)
            {
                throw new AssertionException(string.Format("Element {0} was not found. Page source: {1}{2}",
                                                           by,
                                                           Environment.NewLine,
                                                           driver.PageSource),
                                                           exception);
            }
        }