Selenium With Java and Python For Mobile Apps & Web Apps......!

Thursday, 5 March 2015

Different Types Of Pop Up in Selenium Web Driver.

How To Handle Multiple Windows Navigation Using Web Driver....


import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class WinowHandle {

public static void main(String[] args) throws InterruptedException {

// login to App
WebDriver driver=new FirefoxDriver();
driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// navigate to "time track" page
driver.findElement(By.linkText("Time-Track")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// navigate to "Add task" page
Select sel = new Select(driver.findElement(By.name("selectedUser")));
sel.selectByIndex(1);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// when action causes on "Add tasks" link , which opens new window
driver.findElement(By.linkText("Add tasks to the list")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//get all windows id using getWindowHandles() mtds
Set<String> set = driver.getWindowHandles();

//capture window id from Collection "Set" using iterator
Iterator<String> it = set.iterator();
// get parent and child window Id , & store it in string variable
String parentWindowId = it.next();
String childWindowId = it.next();

//display all window id's
System.out.println(parentWindowId);
System.out.println(childWindowId);

//pass driver control to child window
driver.switchTo().window(childWindowId);

//perform  an operation on child window
driver.findElement(By.xpath("//input[@value='Show Tasks']")).click();

//close child window
driver.close();

// pass control back to parent window
driver.switchTo().window(parentWindowId);

//perform an operation on parent window
driver.findElement(By.linkText("Reports")).click();

}


}



How To Handle  Alert pop up Using Web Driver....


import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AlertHandling {
public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();

driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


//navigate add Projects & Customers page
driver.findElement(By.linkText("Projects & Customers")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


//navigate to customer details page
driver.findElement(By.linkText("sk11")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// click on delete customer , which alert popUP
driver.findElement(By.xpath("//input[@value='Delete This Customer']")).click();

//pass driver control to alert
Alert alt = driver.switchTo().alert();

// perform an operation on alert
System.out.println(alt.getText());

//click on "Cancel" button
//alt.dismiss();

//click on "OK" button
alt.accept();

}

How To Handle Invisible pop up Using Web Driver....


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class InvisiblePopupExample {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.linkText("Projects & Customers")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@style='width: 108pt;']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.name("name")).sendKeys("xyz");
driver.findElement(By.linkText("Reports")).click();
boolean status=driver.findElement(By.xpath("//input[@id='RemainOnThePageButton']")).isEnabled();
if(status)
{
Thread.sleep(3000);
driver.findElement(By.xpath("//input[@id='RemainOnThePageButton']")).click();

}
else {
System.out.println("Invisible pop-up not displayed");
}
}


}


Tuesday, 17 February 2015

Drop Down or Select List in Selenium Web Driver.

Select Class Example....How to handle Select List or Drop Down

package basic;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectClassExample {
public static void main(String[] args) throws InterruptedException {

WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.findElement(By.linkText("Projects & Customers")).click();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 WebElement selectlst=driver.findElement(By.name("selectedCustomer"));
 Select sel=new Select(selectlst);
    sel.selectByIndex(1);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//input[contains(@value,'Show')]")).click();
    Thread.sleep(3000);
    System.out.println("done");
}
}

Or
package app1;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class MultiSelectList {
public static void main(String[] args) throws InterruptedException {

WebDriver driver=new FirefoxDriver();
System.out.println("done");
driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("Reports")).click();
Thread.sleep(2000);
WebElement wb=driver.findElement(By.name("users"));
Select sel=new Select(wb);
System.out.println(sel.isMultiple());
sel.selectByIndex(0);
//sel.selectByIndex(1);

}


}

Dynamic Web List:
package app1;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class DynamicWebList {
public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();
System.out.println("done");
driver.get("http://piyush-pc/login.do");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).click();
WebElement wb=driver.findElement(By.name("customerProject.shownCustomer"));
Select sel=new Select(wb);

List<WebElement> lst = sel.getOptions();

//display size of list
System.out.println(lst.size());
String expval="C";
boolean flag=false;
//display dynamic weblist item name
for (int i = 0; i < lst.size(); i++) {
System.out.println(lst.get(i).getText());
String val=lst.get(i).getText();
if(expval.equals(val))
{
sel.selectByVisibleText(expval);
flag=true;
break;
}
}
if(flag)
{
System.out.println("pass");
}
else {
System.out.println("fails");
}
}


}


Key Board Operation Example :
package basic;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class KeyboardOperationExample {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
String un= driver.findElement(By.name("username")).getAttribute("value");
   System.out.println(un);
//driver.findElement(By.name("pwd")).sendKeys("manager");
Thread.sleep(3000);
Actions act=new Actions(driver);
WebElement wb=driver.findElement(By.xpath("//input[@type='submit']"));
act.moveToElement(wb).perform();


act.sendKeys(Keys.SHIFT,Keys.DELETE).perform();
act.sendKeys(Keys.ENTER).perform();

}


}

Get All Web Elements Example...

package basic;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GetAllWebElementExamole {
public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
String un= driver.findElement(By.name("username")).getAttribute("value");
   System.out.println(un);
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.xpath("//input[@type='submit']")).submit() ;
//to get all link element present in ui
List<WebElement> lst =driver.findElements(By.xpath("//a"));
//to get all web elements
//List<WebElement> lst1 =driver.findElements(By.xpath("//*"));
// System.out.println(lst1.size());
System.out.println(lst.size());

//show all
for (int i = 0; i < lst.size(); i++) {
System.out.println(lst.get(i).getText());


}
for (int i = 0; i < lst1.size(); i++) {
System.out.println(lst1.get(i).getText());

}

}

}


Auto Suggestion.....
package pac1;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AutoSugesstEditBox {

public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in/?gws_rd=cr");
driver.findElement(By.id("gbqfq")).sendKeys("cognizant wiki" ,Keys.ENTER);


}


}



Saturday, 31 January 2015

Basic Program for Webdriver Beginners-3

Basic Example...

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BasicOpExam {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://127.0.0.1/login.do");

System.out.println("current url"+driver.getCurrentUrl());

System.out.println("title of page"+driver.getTitle());

System.out.println("page source code"+driver.getPageSource());

System.out.println("class name"+driver.getClass());

System.out.println("window id"+driver.getWindowHandle());

driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();

driver.manage().window().maximize();

System.out.println("done");

driver.quit();
}

}
WebDriver Wait Example:

package basic;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitStatementExample {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();//launch browser
driver.get("http://piyush-pc/login.do");//navigate to actiTime login page
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");

Thread.sleep(3000);//using java api wait statement
driver.findElement(By.xpath("//input[@type='submit']")).click();
System.out.println("login done");

driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);  //implicit wait statement used wait till entire page get download 
driver.findElement(By.linkText("Projects & Customers")).click();

WebDriverWait wait=new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("add project")));

//explicit wait statement used to load web element not entire page used in dynamic app(ajax app)
System.out.println("done");

}


}



Wednesday, 14 January 2015

How to Launch Multiple Browser in Webdriver

Launch Multiple Browser Example:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;

public class MutlipleBrowserExample {
public static void main(String[] args) {


String browserType="FireFox";
WebDriver driver=null;
if(browserType.equals("FireFox"))

{

driver=new FirefoxDriver();

}
else if (browserType.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver","E:\\SOFTWARES\\chromedriver.

exe");// path of chrome server for Webdriver
WebDriver d=new ChromeDriver();


}
else if (browserType.equals("IE")) {
System.setProperty("webdriver.ie.driver","C:\\Users\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();
capabilities.setBrowserName("safari");
CommandExecutor executor = new SeleneseCommandExecutor(new 
URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);
WebDriver driver = new RemoteWebDriver(executor, capabilities);
}
DesiredCapabilities capabilities = new DesiredCapabilities();

}
}

}


Tuesday, 13 January 2015

Basic Program for Webdriver Beginners-1

To Get Current  PageURL:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CurrentURL {
public static void main(String[] args) {


WebDriver driver=new FirefoxDriver(); 
driver.get("http://advanceseleniumhelp.blogspot.in/");
     Or 
               driver.navigate().to("http://advanceseleniumhelp.blogspot.in/");
   
String s1=driver.getCurrentUrl();
System.out.println(s1);

}
}
To Get Current  Page Title and Page Source(HTML Code):
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class PageTitle{
public static void main(String[] args) {


WebDriver driver=new FirefoxDriver(); 
 driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1"); 

 String s1=driver.getTitle(); System.out.println("Page Title is:"+s1);

String s2=driver.getPageSource();
System.out.println("Page Source code is"+s2);

}
}
Page Refresh and Back Page Navigation:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class PageRefresh {
public static void main(String[] args) throws InterruptedException {


WebDriver driver=new FirefoxDriver();
driver.get("http://advanceseleniumhelp.blogspot.in/");
   driver.navigate().refresh();
   driver.findElement(By.linkText("Brief About Test Automation.")).click();
   Thread.sleep(3000);
   driver.navigate().back();



}

}

Sunday, 11 January 2015

How to launch Diffrent-2 Browsers using Selenium WebDriver?

For Mozilla Firefox:

WebDriver driver=new FireFoxdriver();


Chrome:

System.setProperty("webdriver.chrome.driver","E:\\SOFTWARES\\chromedriver.

exe");// path of chrome server for Webdriver
WebDriver d=new ChromeDriver();


Internet Explorer:
Step 1: Please include below code in a class, code should be before creating an

object

System.setProperty("webdriver.ie.driver","C:\\Users\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

Dwonload IEDriverServer.exe from the below link and store it in your local

machine

(http://code.google.com/p/selenium/downloads/detail?name=IEDriverServer_x64_

2.29.0.zip&can=2&q)

IE need some security settings :

step 2 : (still if u are facing the problems , do the seetings below)

Open up your Internet Explorer settings tools-->Internet Option --> and have a

look at the Security tab. Is the “Enable Protected Mode” checkbox set to the same

value for all the zones



Safari:

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setBrowserName("safari");

CommandExecutor executor = new SeleneseCommandExecutor(new

URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);

WebDriver driver = new RemoteWebDriver(executor, capabilities);

Wednesday, 31 December 2014

Usage of Single ‘/’ and double ‘//’ in the xpath And Absolute Xpath & Relative Xpath

single slash at the start of Xpath instructs XPath engine to look for element starting from root node.
double slash at the start of Xpath instructs XPath engine to search look for matching elementanywhere in the XML document.
Absolute XPath: The easiest way of finding the xpath is to use the Browser Inspector tool to locate an element and  get the xpath of it:
XPath Generated by the tool is : /html/body/div[2]/div/div/footer/section[3]/div/ul/li[3]/a
Relative XPath: At times XPath generated by Firebug are too lengthy and you see there is a possibility of getting a shorter XPath. Above xpath will technically work, but each of those nested relationships will need to be present 100% of the time, or the locator will not function.  Above choosed xpath is known as Absolute xpath. There is a good chance that your xpath will vary in every release. It is always better to choose Relative xpath, as it helps us to reduce the chance of element not found exception.

How To Get Xpath In Different-2 Browser?
Mozilla FireFox: Used FireBug and FirePath plugins for Mozilla link:
http://getfirebug.com/
https://addons.mozilla.org/en-US/firefox/addon/firepath/
Chrome:Here is the steps to do so:

  1. Navigate to the page I want to verify
  2. Press F12 to bring up Chrome debugger
  3. Press ctrl + f to bring up find
  4. Type or paste in the xpath expression that I want to test
  5. See if the xpath found an element.                                                                                                           OR
  1. Open Developer Tools
  2. Select Console tab.
  3. Use $x token. For example, $x("/html/body") will select the body tag.                                                                                                                                                                                                            Internet Explorerhe tool is the Internet Explorer developer bar. What it does show you is the tree (xpath) for the element you click on when you turn the “select element by click” option.                         

Selenium Locators ..............

Selenium web driver uses 8 locators to find the elements on web page. The following are the list of object identifier or locators supported by selenium.
We have prioritized the list of locators to be used when scripting.
1. id
2. Name
3. Linktext
4. Partial Linktext
5. Tag Name
6. class name
7. Css
8. xpath
Locating an Element By ID:
The most efficient way and preferred way to locate an element on a web page is By ID. ID will be the unique on web page which can be easily identified.
IDs are the safest and fastest locator option and should always be the first choice even when there are multiple choices, It is like an Employee Number or Account which will be unique.
Example 1:
<div id="abcid">.....</div>
Example 2:
<input id="email" class="required" type="text"/>
We can write the scripts as
WebElement Ele = driver.findElement(By.id("abcid"));
Unfortunately there are many cases where an element does not have a unique id (or the ids are dynamically generated and unpredictable like GWT). In these cases we need to choose an alternative locator strategy, however if possible we should ask development team of the web application to add few ids to a page specifically for (any) automation testing.
Locating an Element By Name:
When there is no Id to use, the next worth seeing if the desired element has a name attribute. But make sure there the name cannot be unique all the times. If there are multiple names, Selenium will always perform action on the first matching element
Example:
<input name="register" class="required" type="text"/>
WebElement register= driver.findElement(By.name("register"));
Locating an Element By LinkText:
Finding an element with link text is very simple. But make sure, there is only one unique link on the web page. If there are multiple links with the same link text (such as repeated header and footer menu links), in such cases Selenium will perform action on the first matching element with link.
Example:
<a href="seleniumhq.org">Downloads</a>
WebElement download = driver.findElement(By.linkText("Downloads"));
Locating an Element By Partial LinkText:
In the same way as LinkText, PartialLinkText also works in the same pattern.
User can provide partial link text to locate the element.
Example:
<a href="seleniumhq.org">Download selenium server</a>
WebElement download = driver.findElement(By.PartialLinkText("Download"));
Locating an Element By TagName:
TagName can be used with Group elements like , Select and check-boxes / dropdowns.
below is the example code:
Select select = new Select(driver.findElement(By.tagName("value of Tag")));
select.selectByVisibleText("November");
or
select.selectByValue("11");
Locating an Element By Class Name:
There may be multiple elements with the same name, if we just use findElementByClassName,m make sure it is only one. If not the you need to extend using the classname and its sub elements.
Example:
WebElement classtest =driver.findElement(By.className(“value of name”));
CSS Selector:
CSS mainly used to provide style rules for the web pageIs and we can use for identifying one or more elements in the web page using css.
If you start using css selectors to identify elements, you will love the speed when compared with XPath.
We can you use css which can also run with the same speed in IE browser. CSS selector is always the best possible way to locate complex elements in the page.
Example:
WebElement Checkments = driver.findElements(By.cssSelector("input[id="value of id"']"));
XPath Selector:
XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing
There are two types of xpath
1. Native Xpath, it is like directing the xpath to go in direct way. like
Example:
html/head/body/table/tr/td
Here the advantage of specifying native path is, finding an element is very easy as we are mantion the direct path. But if there is any change in the path (if some thing has been added/removed) then that xpath will break.
2. Relative Xpath.
In relative xpath we will provide the relative path, it is like we will tell the xpath to find an element by telling the path in between.
Advantage here is, if at all there is any change in the html that works fine, until unless that particular path has changed. Finding address will be quite difficult as it need to check each and every node to find that path.
Example:
//table/tr/td
We will take and sample XML document and we will explain different methods available to locate an element using Xpath

If a simple XPath is not able to find a complicated web element for our test script, we need to use the functions from XPath 1.0 library. With the combination of these functions, we can create more specific XPath. Let's discuss a 3 such functions –
  1. text():It take complete String with space Ex. //*['text()="abc "']
  2. Normalize-space(): It remove before and after string space not between but not work with part of string.
  3. Contains():It can used remove space and take part of string Ex. //*[contains(.,"hello")]
  4. Sibling: Used in case of dynamic Xpath . Ex. //div/tr[contains(,"hello")]/following-sibling::span //*[contains(text(),"hello")]/preceding-sibling::span
  5. Ancestor

Translate

Popular Posts

Total Pageviews