Elad Benda
Elad Benda

Reputation: 36656

selenium cannot find iframe which appears in my browser

I try to run this code:

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

where farmeBy.selector == #offer-carousel > div > div > div.item.popup.w-control-popup.active > div > div > div > iframe

I get no such element exception.

How can it be if I get a result when I run in chrome inspection tool:

$("#offer-carousel > div > div > div.item.popup.w-control-popup.active > div > div > div > iframe")

Upvotes: 0

Views: 511

Answers (2)

Subh
Subh

Reputation: 4424

I guess you haven't specified the way to access the element.

From the code snippet you've given, you must be trying to use cssselector to locate the element. So, the code can be written like this:

driver.switchTo().frame(driver.findElement(By.cssSelector(frameBy)));

Or else, in case you have a name/id of the frame, you can use the below code:

driver.switchTo().frame("name or id");

Or, you can use the index of the iframe:

driver.switchTo().frame(0);

Note: The above code works only if there is just one iframe in the webpage. In case there are multiple, use the necessary index accordingly.

Upvotes: 1

Stéphane Bruckert
Stéphane Bruckert

Reputation: 22893

I suppose findElement didn't find your iFrame because you didn't specify if frameBy was an ID, a class or anything else. You should use driver.findElement(By.id(frameBy)).

Try the following:

String frameBy = "YOUR_FRAME_ID";
WebElement iFrame = driver.findElement(By.id(frameBy));
driver.switchTo().frame(iFrame);

Here is an alternative way that searches the first iframe no matter what your iframe ID is:

driver.switchTo().frame(driver.findElements(By.tagName("iframe").get(0));

Upvotes: 1

Related Questions