Reputation: 93
I am trying to click through all of these nested links inside a mouse over web element. The first iteration works, but it stops after that. I've tried adding Thread.Sleep(xxxx);
but that doesn't work either. Here's my method:
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;
}
Again, this works for one iteration. Any help is appreciated.
Upvotes: 2
Views: 2730
Reputation: 16201
Instead of hard coded index number you should find the target elements with FindElements
then loop though and click back and forth.
Second think, you need to use proper wait time to make sure the elements are loaded properly.
Third, Need to find the element on the fly cannot simply iterate through the collection and click back and forth. It will refresh the DOM
and throw StaleElement
reference exception.
Here is a sample test which is doing the same thing you are trying to do
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));
}
}
Upvotes: 1