在selenium / webdriver c#中循环多个moveToElement

时间:2015-01-14 21:07:21

标签: c# selenium selenium-webdriver

我试图点击鼠标在web元素上的所有这些嵌套链接。第一次迭代有效,但在此之后停止。我尝试添加Thread.Sleep(xxxx);,但这也不起作用。这是我的方法:

public static bool TestFindAssets()
    {
        bool result = false;
        Actions action = new Actions(driver);
        var findAssetsClick = driver.FindElement(By.XPath("/html/body/div/header/nav/ul/li[3]/a"));
        var home = driver.FindElement(By.LinkText("Home"));
        try
        {

            for (int i = 1; i < 13; i++)
            {
                action.MoveToElement(findAssetsClick).Perform(); //Find Assets Link
                action.MoveToElement(driver.FindElement(By.XPath("xpath"))).Perform(); //By Type Link
                action.MoveToElement(driver.FindElement(By.XPath("otherPath"+i))).Click().Build().Perform(); //list of links

            }

             result = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occurred: ", ex);
            result = false;
        }

        return result;
    }

同样,这适用于一次迭代。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您应该找到带有FindElements的目标元素,而不是硬编码索引号,然后循环播放并来回点击。 其次,您需要使用适当的等待时间来确保元素正确加载。 第三,需要在运行中找到元素不能简单地遍历集合并来回点击。它将刷新DOM并抛出StaleElement引用异常。

这是一个示例测试,它正在尝试做同样的事情

public void ClickThroughLinks()
{
    Driver.Navigate().GoToUrl("http://www.cnn.com/");
    //Maximize the window so that the list can be gathered successfully.
    Driver.Manage().Window.Maximize();

    //find the list
    By xPath = By.XPath("//h2[.='The Latest']/../li//a");
    IReadOnlyCollection<IWebElement> linkCollection = Driver.FindElements(xPath);

    for (int i = 0; i < linkCollection.Count; i++)
    {
        //wait for the elements to be exist
        new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(xPath));

        //Click on the elements by index
        Driver.FindElements(xPath)[i].Click();
        Driver.Navigate().Back();
        Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(10));
    }
}