Search code examples
seleniumfirebugfirepath

Selenium Webdriver : I am not able to switch to iframe


Here is the code that I have written.I have tried adding thread.sleep() but it still doesn't work also tried with chromedriver but same result

package com.thinksys.frames;

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

public class Iframes 
{
    public static void main(String[] args) 
    {
        System.setProperty("webdriver.gecko.driver","C:\\Users\\thinksysuser\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");

        WebElement e = driver.findElement(By.id("google_ads_iframe_/37179215/DFP_NGET_01_HomePage_RHS_ATF_479x266_ENG_0"));

        driver.switchTo().frame(e);

        driver.findElement(By.xpath(".//*[@id='image-11']/a/img")).click();
    }
}

Solution

  • It might caused by the special characters in the <ifram> id. Using partial id will provide two matches, so I suggest you use two portions of the name attribute

    WebElement frame = driver.findElement(By.cssSelector("[name*='google_ads_iframe'][name*='DFP_NGET_01_HomePage_RHS']"));
    driver.switchTo().frame(frame);
    

    Edit

    The images rotates, each on is visible for a few seconds only. To click on a specific image you need to wait for it to be visible. You can use explicit wait for it

    WebDriverWait wait = new WebDriverWait(driver, 60, 50);
    wait.until(ExpectedConditions.visibilityOfElementLocatedBy.xpath(".//*[@id='image-11']/a/img"))).click();
    

    This will pole the DOM every 100 milliseconds until the image is visible or the time is up (60 seconds).