The html code shows 4 iframes present and the accept button is within a nested iframe. However, I cant seem to switch to the second iframe (I’ve tried indexes,locators, and names) where the button is, I get an error saying the iframe can’t be found. If anyone can solve this, it would greatly impact my learning journey. Thank you!
I have tried the following:
driver.get("https://www.jetblue.com/");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.switchTo().frame(0);
driver.switchTo().frame(1);
//Accept cookies locator
driver.findElement(By.xpath("//div[@class='pdynamicbutton']/a")).click();
2
Answers
Switching into nested frames can be tricky, but it’s definitely possible. One thing you need to understand is that each time you use driver.switchTo().frame(), WebDriver will start looking for frames that are direct children of the current context. When you are at the top level, you’re in the context of the html element. If you switch into a frame, you’re now in the context of that frame.
In your code, when you try to switch to frame 0 and then immediately try to switch to frame 1, WebDriver will look for the second frame inside the first frame. However, if they are sibling frames (i.e., both direct children of the main document), the second switch will fail, because there is no second frame inside the first frame.
If the "Accept cookies" button is in the second frame at the top level, you should switch back to the default content before switching to the second frame. Here’s how:
Also, keep in mind that frames can be indexed from 0, so the second frame would have index 1.
Lastly, always make sure the element you’re looking for is actually in the frame you think it’s in. If you’re not sure, you can inspect the HTML of the page and look for iframe or frame tags and follow them down to find out where the element is.
In your specific case, also make sure to wait until the page is fully loaded and all frames are available before trying to switch to them. As this website might use dynamic content loading, you might need to use WebDriverWait and ExpectedConditions.frameToBeAvailableAndSwitchToIt.
If you notice the HTML DOM(See below), there is only one IFRAME within which the desired element is located. So you need to worry only about one IFRAME.
Refer the below working code: