Search code examples
javaselenium-webdriveriframe

Selenium Java: Can't get an access to elements inside IFRAME


I need to get an access to the elements inside iframe id = "myFrame" on the web page https://cloud.google.com/products/calculator-legacy

I've tried this solution, but it didn't work:

By frameXpath = By.xpath("//iframe[@id='myFrame']");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameXpath));

WebElement frame = driver.findElement(frameXpath);
driver.switchTo().frame(frame);

Also I've tried this solution, but it didn't work too:

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//devsite-iframe/iframe")));

By frameXpath = By.xpath("//iframe[@id='myFrame']");

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameXpath));

driver.switchTo().frame(driver.findElement(frameXpath));

I have an exception:

"NoSuchElementException: Unable to locate element: //iframe[@id='myFrame']"

Is there a way to get an access to the elements to set the conditions for the estimation? Thank you!


Solution

  • There were a couple issues

    1. You missed an IFRAME above the "myFrame" IFRAME.

    <iframe src="https://cloud.google.com/frame/products/calculator-legacy/index_d6a98ba38837346d20babc06ff2153b68c2990fa24322fe52c5f83ec3a78c6a0.frame" allow="clipboard-write https://cloud-dot-devsite-v2-prod.appspot.com" allowfullscreen="" name="goog_1486242109">

    1. You were using .frameToBeAvailableAndSwitchToIt() but then attempting to switch to the IFRAME again. .frameToBeAvailableAndSwitchToIt() waits for the IFRAME and then switches to it... so there's no need to switch to it again.

    Working code is below. It switches into the two IFRAMES and then sets the "Number of instances" field to "1".

    import java.time.Duration;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    ...
    
    String url = "https://cloud.google.com/products/calculator-legacy";
    
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get(url);
    
    String numberOfInstances = "1";
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("#cloud-site iframe")));
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("myFrame")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("form[name='ComputeEngineForm'] input[ng-model='listingCtrl.computeServer.quantity']"))).sendKeys(numberOfInstances);