Search code examples
javaseleniumselenium-webdriveriframewebdriverwait

How to click element within multiple nested iframe using Selenium


While clickig the element inside the iframe getting selenium timeout of no such frame element exception . It's the RedBus web application I am using.

I tried with the driver switch to ().the frame("gsi_934517_585705"); with id, Name, index too but no success.

WebDriver driver= new ChromeDriver();
driver.get("https://www.redbus.in/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//div[@id='signin-block']")).click();      
driver.findElement(By.xpath("//li[@id='signInLink' and text()='Sign In/Sign Up']")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2000));
//Thread.sleep(50000);
driver.switchTo().frame("gsi_934517_585705");
driver.findElement(By.xpath("//span[text()='Sign in with Google' and @class='nsm7Bb-HzV7m-LgbsSe-BPrWId']")).click();
driver.close();

Solution

  • The below line of code won't switch to the required iframe because the ID is dynamic and each time you execute, the iframe id is different.

    driver.switchTo().frame("gsi_934517_585705");
    

    Try the below code:

    driver.get("https://www.redbus.in/");
    driver.findElement(By.xpath("//div[@id='signin-block']")).click();      
    driver.findElement(By.xpath("//li[@id='signInLink' and text()='Sign In/Sign 
        Up']")).click();
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    int size = driver.findElements(By.tagName("iframe")).size();
    //System.out.println("no of iframes" + size);
    //There are 2 iframes,we are interested in the second one,hence the below line
    driver.switchTo().frame(1);
    driver.findElement(By.xpath("//span[text()='Sign in with Google' and @class='nsm7Bb-HzV7m-LgbsSe-BPrWId']")).click();
    driver.close();
    

    Basically, get the number of iframes and switch to the iframe you want based on its index. Good luck. Upvote if this answers and solves your query,