Khan
Khan

Reputation: 342

Unable to locate an element in frame

Below is my code :-

package Practice;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Day6FramesRecap {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.google.com/recaptcha/api2/demo");
    int framenumber = frameset(driver,By.xpath(".//*[@id='recaptcha-anchor']/div[5]"));
    driver.switchTo().frame(framenumber);
    driver.findElement(By.xpath(".//*[@id='recaptcha-anchor']/div[5]")).click();
    driver.switchTo().defaultContent();
    try{
        Thread.sleep(1000);
        }catch(InterruptedException e){
        e.printStackTrace();
        }
    int framenumber2 = frameset(driver,By.xpath(".//*[@id='recaptcha-verify-button']"));
    driver.switchTo().frame(framenumber2);
    driver.findElement(By.xpath(".//*[@id='recaptcha-verify-button']")).click();


}
public static int frameset(WebDriver driver, By by)
{
    int i;
    int framecount= driver.findElements(By.tagName("iframe")).size();
    for(i=0;i<framecount;i++)
    {
        driver.switchTo().frame(i);

        int count = driver.findElements(by).size();
        if(count>0)
        {
            break;

        }
        else
        {
            System.out.println("Continue Looping");
        }
    }
    driver.switchTo().defaultContent();
    return i;
}

}

What i am trying to do is , use the for loop to iterate through each frame and find the element I need. However, I am able to find the first element i.e. By.xpath(".//*[@id='recaptcha-anchor']/div[5] and after clicking that, I am not able to click on the second element By.xpath(".//*[@id='recaptcha-verify-button']

I encounter an error stating that :-

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='recaptcha-verify-button']"}

Upvotes: 0

Views: 3440

Answers (1)

Ravikar Bhardwaj
Ravikar Bhardwaj

Reputation: 317

You can switch between the iframes using WebElements. You can try the following code,

public static void main(String args[]) throws InterruptedException
{

        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com/recaptcha/api2/demo");

        WebElement frame = driver.findElement(By.xpath(".//iframe[@title='recaptcha widget']"));

        driver.switchTo().frame(frame);

        driver.findElement(By.xpath(".//*[@id='recaptcha-anchor']/div[5]")).click();
        driver.switchTo().defaultContent();

        Thread.sleep(2000);

        WebElement frame1 = driver.findElement(By.xpath(".//iframe[@title='recaptcha challenge']"));
        driver.switchTo().frame(frame1);
        driver.findElement(By.xpath(".//*[@id='recaptcha-verify-button']")).click(); // this will click on the [Verify] button.
}

Upvotes: 4

Related Questions