How do I select elements inside an iframe with Xpath?

Question:

I want to create a Selenium test to test our extensions with AOL mail. I managed to login to AOL and compose an email, but I also need to select elements inside the editor, which is inside an iframe. I checked and even when the editor is open the following test fails:

self.assertEqual(first=1, second=len(self.driver.find_elements_by_xpath(xpath="//iframe[@name='editor_body']//body[@contenteditable='true']")))

I get the error AssertionError: 1 != 0. How do I select the body of the iframe and other elements by Xpath (or in any other way with Selenium)?

Asked By: Uri

||

Answers:

You cannot traverse through <iframe>‘s until switching to them. Your xPath,

//iframe[@name='editor_body']//body[@contenteditable='true']

will not work because the <body> tag is within an iFrame, which is not in the current context. you need to switch to it first:

driver.switch_to.frame('editor_body')...
Answered By: ddavison

In case you are facing issues during Selenium automation testing here is some info that solved my problem:

by default has access to the parent browser driver. In order to access inside a frame, the driver’s focus has to shift from the main browser window to the frame.

Therefore, if you happen to have to do assertions inside an iframe and then go back to the main window to do other interactions you will need to change the Driver’s focus based on your target.

Read more at: https://www.tutorialspoint.com/how-do-i-select-elements-inside-an-iframe-with-xpath

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.