I'm trying to select an element that resides within an iframe and may reside within other iframes.
Is it possible to select an element within some (child) iframe in (python) selenium without selecting the iframe first? Is there a way to somehow "loop" through each iframe and check where my element can be found...?
How to do this in case the element, html content and iframe may have just been loaded...?
P粉5712335202024-02-27 10:09:53
It should be easy to write your own recursive finder. Sorry, I don't know python, but in Java it would look like this:
public void findInAllFrames(WebElement e, String targetIdStr) { Listl = e.findElements(By.tagName("iframe")); for(int inx=0; inx targets = l.get(inx).findElements(By.id(targetIdStr)); if(targets.size()>0) { // Do something with your targets } findInAllFrames(l.get(inx), targetIdStr); } }
P粉7948519752024-02-27 10:03:34
No, cannot pass Selenium, no need to switch to the corresponding iframe
.
When loading a page, Selenium's focus remains on the top window by default. Top window contains other <iframes>
and framesets. Therefore, when we need to interact with a WebElement inside an iframe, we must switch to the corresponding <iframe>
via one of the following methods:
We can switch to the frame in 3 ways.
By frame name:
Name The attribute of iframe through which we can switch to it.
Example:
driver.switch_to.frame("iframe_name")
By frame ID:
TheID attribute of iframe, through which we can switch to it.
Example:
driver.switch_to.frame("iframe_id")
Index by frame:
Assuming that the page has 10 frames, we can switch to iframe through index.
Example:
driver.switch_to.frame(0) driver.switch_to.frame(1)
Switch back to host:
We can use default_content()
or parent_frame()
to switch back to the main frame
Example:
driver.switch_to.default_content() driver.switch_to.parent_frame()
A better way to switch frames is to induce WebDriverWait# by setting
expected_conditions to
frame_to_be_available_and_switch_to_it
## To get the availability of the expected framework as follows:
Frame ID:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.ID,"id_of_iframe"))Frame name:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"name_of_iframe")))FrameworkXpath:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"xpath_of_iframe")))Frame CSS:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"css_of_iframe")))