Selenium WebDriver With Simple Examples
Below are the examples of switching frames, getting text of an element of alert box and print it out on console, input data if field is displayed and enabled which helps for the selenium beginners.
Examples written in the order explained above.
public class demoSwitchFrames {
FirefoxDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
driver.get("http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html");
}
// @Test
// public void shouldSwitchToNewFrame()
//
// {
// driver.switchTo().frame("classFrame");
// driver.findElement(By.linkText("Deprecated")).click();
// driver.close();
//
// }
@Test
public void shouldSwitchToNewFrame()
{
driver.switchTo().frame("packageListFrame");
driver.findElement(By.linkText("org.openqa.selenium")).click();
driver.findElement(By.linkText("org.openqa.selenium.remote.html5")).click();
driver.close();
}
}
If
the application under test contains frames, then we need to switch the
WebDriver control to that frame before interacting with the element
inside the frame.
There are three ways to switch the frames...
First method is using frame name:
driver.switchTo().frame("frameName");
Second is using frame index (Zero based):
driver.switchTo().frame(1);
And to come back to default frame:
driver.switchTo().defaultContent();
So in this way we can play around the different frames and can apply click event to select particular option inside the frames.
The best way to use is by iframeID
//get the number of frames available
System.out.println("The number of iFrames are " webdriver.findElements(By.tagName("iframe")).size());
//if only 1 frame available, then get(0)
webdriver.switchTo().frame(webdriver.findElements(By.tagName("iframe")).get(0));
//if more than 1 frame, get the size and move the frame of your choice
____________________________________________________________________________
public class demoGettingTextOnAlertBox {
FirefoxDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
driver.get("http://jsbin.com/usidix/1");
}
@Test
public void TextonAlert() throws InterruptedException {
// css=input[type="button"]
driver.findElement(By.cssSelector("input[type=\"button\"]")).click();
String text = driver.switchTo().alert().getText();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.switchTo().alert().accept();
System.out.println(text);
}
}
________________________________________________________________________________
public class demoInputDataDisplayEnabled {
FirefoxDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
driver.get("http://newtours.demoaut.com/");
}
@Test
public void displayEnabled ()
{
WebElement username = driver.findElement(By.name("userName"));
if(username.isDisplayed() && username.isEnabled());
{
username.sendKeys("Softedge100");
}
}
}
________________________________________________________________________________
No comments:
Post a Comment