Moving back to parent frame in Selenium

2019-03-06 12:04发布

问题:

For moving back to parent frame in Selenium, driver.switchTo().parentFrame(); is used. In my example website, I achieved same functionality using driver.switchTo().defaultContent(); also.

Is there any functional difference between these two:

- driver.switchTo().parentFrame();
- driver.switchTo().defaultContent();

While referring to frames in a HTML document, are "Parent Frame" and "Default Content" different? Please explain.

回答1:

It does have difference to an extent. Suppose you have a page having frame 'three' inside a frame 'two' inside another frame 'one', considering that you are on the frame 'three' which is inner most...

driver.switchTo().parentFrame(); - This will shift focus back to frame 'two'. driver.switchTo().defaultContent(); - This will shift focus back to main (default) content in which frame 'one' lies.

I hope this was helpful. Thanks !



回答2:

If you only have two frames on a page, there is no functional difference. However, the app I'm working on has as many as 5 nested frames on a page.

For example, I need to work with two elements that are at the third frame, step inside another frame, then step back to work with another element in frame 3. I have two choices to accomplish this.

1: I can step all the way out and then back in

//click element 1
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame1")));
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame2")));
driver.FindElement(By.Id("element1")).Click();
//click element 2
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame1")));
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame3")));
driver.FindElement(By.Id("element2")).Click();

The other option is to switch to the parent frame.

//click element 1
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame1")));
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame2")));
driver.FindElement(By.Id("element1")).Click();
//click element 2
driver.SwitchTo().ParentFrame();
driver.SwitchTo().Frame(driver.FindElement(By.Id("Frame3")));
driver.FindElement(By.Id("element2")).Click();

Basically, it saves the effort of writing code to switch all the way back out then back into the frame if you only need to move back one level.