Selenium Webdriver Study (v) Treatment of------------iframe
Blog Category:
How to position elements in a frame
Sometimes when we locate a page element, we find that we can't locate it, and check the locator that we wrote repeatedly without any problems, and the code doesn't have any problems. At this point you will have to look at whether this page element is in an IFRAME, which may be one of the reasons why you cannot find it. If you are looking for an element in the IFRAME in a default content, it must not be found. Conversely, if you look for another IFRAME element in an IFRAME or an element in the default content, it must not be located.
The selenium Webdriver provides a way to enter an IFRAME:
Webdriver Org.openqa.selenium.WebDriver.TargetLocator.frame (String nameorid)
It also provides a way to return the default content:
Webdriver Org.openqa.selenium.WebDriver.TargetLocator.defaultContent ()
This makes it easy for us to deal with the IFRAME.
Take the following HTML code as an example, and let's look at a current IFRAME.
HTML code
- Main.html
- <html>
- <head>
- <title>frametest</title>
- </head>
- <body>
- <div id = "ID1" >this is a div! </div>
- <iframe id = "frame" frameborder="0" scrolling= "no" style="left:0; Position:absolute; " src = "frame.html"></iframe>
- </Body>
- </html>
- Frame.html
- <html>
- <head>
- <title>this is a frame! </title>
- </head>
- <body>
- <div id = "div1">this is a div,too! </div>
- <label>input:</label>
- <input id = "input1"></input>
- </Body>
- </html>
Java code
- Import Org.openqa.selenium.By;
- Import Org.openqa.selenium.WebDriver;
- Import Org.openqa.selenium.firefox.FirefoxDriver;
- Public class Famestudy {
- public static void Main (string[] args) {
- Webdriver dr = new Firefoxdriver ();
- String url = "\\Your\\Path\\to\\main.html";
- Dr.get (URL);
- //In the default content location id= "Id1" div
- Dr.findelement (By.id ("ID1"));
- //At this time, do not enter into the id= "frame" frame, the following two sentences will be error
- Dr.findelement (By.id ("Div1")); Error
- Dr.findelement (By.id ("input1")); Error
- //Enter the frame of id= "frame" to locate the id= "Div1" div and the input box id= "INPUT1".
- Dr.switchto (). FRAME ("frame");
- Dr.findelement (By.id ("Div1"));
- Dr.findelement (By.id ("input1"));
- //At this point, if you do not jump out of frame, you will get an error if you locate the element in default content.
- Dr.findelement (By.id ("ID1")); Error
- //Jump out of frame, go to default content, reposition id= "Id1" div
- Dr.switchto (). Defaultcontent ();
- Dr.findelement (By.id ("ID1"));
- }
- }
The switch_to method new1 A Targetlocator object, using the object's frame method to move the currently recognized "body" to the frame that needs to be positioned.
Selenium Webdriver Learning (v) Processing of------------iframe (RPM)