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

我试图通过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; } 

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

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

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

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