Reputation: 11
I want to switch to an iframe which contains some links in it. I need to switch to that iframe and click the links one by one. Here is my code,
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://timesofindia.indiatimes.com/home");
WebDriverWait wait = new WebDriverWait(driver,200);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("riShop")));
driver.switchTo().frame("riShop");
List<WebElement> lst = driver.findElements(By.tagName("a"));
for(int i = 0; i < lst.size(); i++) {
lst.get(i).click();
driver.navigate().back();
}
}
In the above code only the first link gets clicked and then I get an exception like "unable to locate the next element" NoSuchException
How do I fix this?
Upvotes: 0
Views: 1022
Reputation: 1484
Following is the code which i tried for Google site.
Put extra validation as link.getText() as many links with empty texts may exists and link.click may not work there. So just make the "if" condition before clicking on it as specified in below code
public static void main(String[] args)
{
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
for (int i=0; true; i++)
{
List<WebElement> links = driver.findElements(By.tagName("a"));
if (i >= links.size())
break;
if(!links.get(i).getText().isEmpty())
{
links.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
}
}
The logic is simple each iteration in the for loop re-identifies the object but we are navigating to next link by increasing the index value.
Upvotes: 1
Reputation: 1484
Is your Exception is NoSuchElement or StaleElementException error?
I am hoping the error is StaleElementException. Reason being, when you navigate away from the page and once you come back. previous objects will become "Stale".
Following is the logic which i got from SO when i faced this problem earlier:
for (int i=0; true; i++)
{
List<WebElement> links = driver.findElements(By.tagName("a"));
if (i >= links.size())
break;
links.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
Let us know if the above helps.
Upvotes: 1