"Karmanyevadhikaraste ma phaleshu kadachana, Ma karma phala hetur bhurmatey sangostva akarmani."

DB connection

Install my sql

In selenium, write code as

import java.sql.*
public class Db_connect{

connection conn=null;

String url= jdbc:mysql://localhost:3306/";
String DBName="Test"  (Table name)
String driver="com.mysql.jdbc.Driver";
String username="kkjkj"

String password="fff";

try{
class.forName(driver).newInstance();  //create object of instance of driver
conn=DriverManager.getconnection(url+dbname+username,[password) //get connection
Statement stmt= conn.createstatement();
resultset s= stmt.executequery("select * from users");

rs.next();
syso(rs.getstring(1);

while(rs.next)
syso(rs.getstring(1)

Prepare statement pp=conn.prepare statement
pp.setstring(1,"p");
resultset rs3=pp1.executequery();


}catch(Exception e)
{
finally

conn.close();

Grid-type pf connections

We can start hub in remote machine using vmware start a node there and start a node in local machine connecting to vmware hub and run tests parallel
we can use webconfig configuration file to configure

now the tests has ran parallelely...parallel="tests" threadcount="10"> in xml file..
now want to run them at a time

parallel="classes"  >

Grid-Example















Connecting Grid:

1. Start the Hub:

java -jar selenium-server-standalone-2.14.0.jar -role hub

The hub will automatically start-up using port 4444 by default
to change java -jar selenium-server-standalone-2.39.0.jar -role hub -port 4441

2. Start the nodes


java -jar selenium-server-standalone-2.39.0.jar -role node -hub http://localhost:4444/grid/register


java -jar selenium-server-standalone-2.14.0.jar -role node -hub http://
localhost:4441/grid/register -nodecongig webconfig.txt -port 5556 http://
localhost:4441/grid/console  -browser browserName=firefox,version=3.6,maxinstances=5,platform=WINDOWS -nodecongig webconfig.txt


java -Dwebdriver.chrome.driver="C:\chromedriver.exe" -Dwebdriver.ie.dr
iver="C:\IEDriverServer.exe" -jar selenium-server-standalone-2.39.0.jar -role webdriver -hub http://
localhost:4441/grid/register -port5557 -browser browserName=firefox -browser browserName=chrome -browser browserName=iexplorer nodeTimeout 300



3. Create script to run using  DesiredCapabilities capability = DesiredCapabilities.firefox();
and Pass that into the RemoteWebDriver object:


WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);



4. create a testng.xml file and keep the tests in there, and run test ng Suite

You can view the status of the hub by opening a browser window and navigating to: http://localhost:4444/grid/console






import java.net.MalformedURLException;
import java.net.URL;

//import net.sourceforge.htmlunit.corejs.javascript.ast.ThrowStatement;

//import org.apache.xerces.util.URI.MalformedURIException;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
//import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;



public class Grid_demo3 {

@Parameters("browser")
@Test
public void Google_Serach(String b) throws MalformedURLException {
//pass the browser in the search function and print
System.out.println(b);

//make desired capability to null and give if else conditions for multiple change of browsers
DesiredCapabilities cap = null;

if(b.equals("firefox")){
cap= DesiredCapabilities.firefox();
 cap.setPlatform(Platform.ANY);
 cap.setBrowserName("firefox");
}else if (b.equals("chrome")){
cap= DesiredCapabilities.chrome();
cap.setPlatform(Platform.ANY);
 cap.setBrowserName("chrome");}
else if (b.equals("iexplore")){
cap= DesiredCapabilities.internetExplorer();
cap.setPlatform(Platform.WINDOWS);
 cap.setBrowserName("iexplore");}


//no need to give path of chrome exe as we r giving it in node
//C:\Meeraja-Selenium\libraries>java -Dwebdriver.chrome.driver=C:\chromedriver.exe -jar selenium-serve
// r-standalone-2.39.0.jar -role webdriver -hub http://localhost:4441/grid/register -port5557 -browser
// browserName=firefox -browser browserName=chrome


RemoteWebDriver driver= new RemoteWebDriver(new URL("http://localhost:4441/wd/hub"),cap);
driver.get("http://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("meera");
driver.findElement(By.id("Passwd")).sendKeys("ana");

 }
}

test.xml

<suite name="Selenium Grid with webdriver" verbose="3" parallel="tests">
  <test name="Grid_demo3" >
  <parameter name="browser" value="iexplore"/>
      <classes>
        <class name="Grid_demo3" />
  </classes>
  </test>
</suite>



xml elements should be properly nested
xml tags are case sensitive
xml tags should have root element
xml element attributes should be in quotes

  <parameter name="browser" value="iexplore"/>
xml tags should have closing tags


setup node-selenium grid

C:\Meeraja-Selenium\libraries>java -Dwebdriver.chrome.driver="C:\chromedriver.exe" -Dwebdriver.ie.dr
iver="C:\IEDriverServer.exe" -jar selenium-server-standalone-2.39.0.jar -role webdriver -hub http://
localhost:4441/grid/register -port5557 -browser browserName=firefox -browser browserName=chrome -bro
wser browserName=iexplorer nodeTimeout 300

MOuse movements

public class Mous_move {


public static void main(String[]args){


WebDriver mydriver = new FirefoxDriver();
EventFiringWebDriver webdriver= new EventFiringWebDriver(mydriver);
MyListener myListner= new MyListener();
mydriver.register(myListener);

mydriver.navigate("http://timesofindia.com");

Download file using selenium

in firefox, give   about:config  will give verious properties of forefox

there r d/f type of files,

rar file

doc file

exe file

create a firefox profile
FirefoxProfile profile= new FirefoxProfile();
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.dir","D:\\test");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/msword,etc");

Go Back and Forward buttons


public class Front_BackButttons {

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

WebDriver driver =new FirefoxDriver();
driver.navigate().to("http://google.com");
//navigate only have functions to go forwrad or backward
driver.findElement(By.xpath("ddsds"));
Thread.sleep(5000L);

driver.navigate().back();
Thread.sleep(5000L);
driver.navigate().forward();
Thread.sleep(5000L);
driver.quit();

wells batch testing reqs

Test Design and Test Execution for Digital Payments (Direct Pay). 
Batch Testing using Autosys, Working with Flat file formats, Data Validation using SQL/Toad and Unix. 
Must have Financial Institution test experience.
HR Job Description:
-          Creates, prepares and implements systems quality assurance reviews for numerous applications. Responsible for primary development of testing strategies.  
-          Consults with users, providing advice and direction.  
-          Performs more complex analysis of business requirements and system specifications.   
-          May serve as a coordinator for all testing activities on a project.  
-          Creates test plans and scripts for own projects.  
-          May lead and review test plans written by others.  
-          Performs moderately complex to complex test data conditioning, regression testing and testing validation.  
-          Provides specific guidance on defects to developers. 
-          Gives direction to less experienced analysts.   
-          Logs, tracks, and verifies resolution of software and specification defects.   
-          Documents all phases of the Systems QA process.: 
-          5+ years IT quality assurance and systems/application testing experience.

Java Script Alerts

go to rediff..
sign on click

don't enter email and click enter...alert will popup with msg enter email


public class Alerts {

public static void main(String[] args) throws InterruptedException {
WebDriver driver= new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://www.rediff.com");
driver.findElement(By.linkText("signin ")).click();

driver.findElement(By.xpath("//*[@id='btn_login']")).sendKeys(Keys.ENTER);
Thread.sleep(1000L);
Alert Al= driver.switchTo().alert();
System.out.println(Al.getText());
Al.accept();//means OK
//Al.dismss(); //Cancel
//To switch back to regular page
driver.switchTo().defaultContent();

Handling Calenders

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
public class Calender_Handle {

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


String d = "24/04/2014";
////first we need to extract month and date
SimpleDateFormat df= new SimpleDateFormat("dd/mm/yyyy");
Date myDate = df.parse(d);
Calendar cal= Calendar.getInstance();
cal.setTime(myDate);

int day= cal.get(Calender.Day

File upload

//for file upload always input type is File and id = multi type file

WebDriver driver= new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://www.salesforce.com");
driver.findElement(By.xpath("//login']")).click();
driver.findElement(By.xpath("//*[@id='u_0_n']")).sendKeys("user");
driver.findElement(By.xpath("//*[@id='u_0_n']")).sendKeys("pwd");
driver.findElement(By.xpath("//*[@id='u_0_n']")).sendKeys(Keys.ENTER);
driver.findElement(By.xpath("//File_Tab']")).click();

driver.findElement(By.xpath("//input[@id='multiFileInput']")).sendKeys("c:\\ssccc.jpeg");


//select File  option some times is flash ...

managing web table with css

WebDriver driver= new FirefoxDriver();
driver.get("http://www.timeanddate.com/worldclock");


//html/body/div[8]/table/tbody/tr[2]/td[3]/a
//under table with class name <table class="border2 lpad wa wc-tab ccols4">
//String xpath="//table[@class='border2 lpad wa wc-tab ccols4']/tbody//tr[2]/td[3]/a";

// to write it as css selector

String cSelect = "table[class= 'border2 lpad wa wc-tab ccols4'] tbody tr:nth-child(2) td:nth-child(3) a";

System.out.println(driver.findElement(By.cssSelector(cSelect)).getText());

Element present at xpath

public boolean isElementPresent_xpath(String objectXpath){
int count=driver.findElement(By.xpath(objectXpath)).size();
if(count==0)
return false;
else
return true;


String firstname="Meeraj";
String lastname="Anasuri";
Assume names are in  a web table,
//Validations:

String part1="//*@id='hkjhjkh[" ;
String part2="]/td[2]";
int i=2 // as xpath starts at 2 for this
while( isElementPresent_xpath(part1+i+part2))
String fname=driver.findElement(By.xpath(part1+i+part2).getText();
if(fName.equals(firstname)){

//then check for last name

String xpathLastnamecol= part1+i+part2.replace("td[1]","[2]");
String lName=driver.findElement(by. xpathLastnamecol).getText();
if(lName.equals(LastName)){
system.out.println();
recordFound=true;
break;
}}

Assert.assertTrue(recordFound,"Record of full name");

cookies

cookies-to keep session of users browser place some code in u r

driver.get("http://www.neocell.com");

Set<Cookie> cookies= driver.manage().getCookies();
//there r multiple options to get cookies,delete cookies,add cookies etc
//cookie is a inbuilt class

System.out.println("Total Cookies" +cookies.size());

Iterator<Cookie> iter= cookies.iterator();

while(iter.hasNext()){
Cookie c= iter.next();
System.out.println(c.getDomain() + "----" + c.getName() +"---" +c.getValue());                      // the website which cookie belongs to and get the name of the cookie and the value of cookie

}

//driver.manage().deleteAllCookies();
//driver.manage().deleteCookieNamed("name");

webdriver timeouts


webdriver timeouts:

driver.get("http://www.gmail.com");

//timeouts will wait for the elemnt to load
// suppose  we give 5 sec, 5 sec is max time it waits and throws error then, if it ready in 3 sec, it will continue
//pageloading time- for the next page to load
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
WebElement table= driver.findElement(By.xpath("//*[@id='Passwd']")).sendKeys(keysToSend);;



Frames:

like  apage inside a page..

tag name iframe
there will be multiple iframes in a page- o ask developer about iframe
go to page source, find the link name and made own xpath

to switch frame

driver.switchTo().frame(1)  //control to 1 st frame

to find no.of frames in a web page, 
driver.findelement by tagname(iframe).size();

WebDriver driver= new FirefoxDriver();

driver.get("http://www.timesofindia.com");
System.out.println(driver.findElements(By.tagName("iframe")).size());//no.of frames in a page
//switch to frame
driver.switchTo().frame("liveScores");//get it from page source
//once move to the required frame, then click on url
//to kniw, if it is frame or not, right clcik on it and will see the option frame
driver.findElement(By.xpath("ccc"));


Frame inside Frame:

driver.get("http://www.borro.com");
driver.findElement(By.xpath("kkjkj")).click();
Thread.sleep(1000L);
//ligbox loaded
List<WebElement> frames= driver.findElements(By.tagName("iframe"));
System.out.println(frames.size());
System.out.println(frames.get(0).getAttribute("id"));//particular element
System.out.println(frames.get(1).getAttribute("id"));//2nd element

driver.switchTo().frame(1);
driver.findElement(By.xpath("kkjkj")).sendKeys("jj");
}

Reading the web table contents-rows and column data

public class Web_Tables {

public static void main(String[] args) {
//no.of rows in table

WebDriver driver= new FirefoxDriver();

driver.get("http://www.w3schools.com/tags/tag_table.asp");
WebElement table= driver.findElement(By.xpath("//*[@id='main']/table[2]")); //partial xpath
List<WebElement> rows= table.findElements(By.tagName("tr"));//retrive all rows with tag tr
System.out.println("no.of rows " + rows.size());

for(int rownum=1;rownum<rows.size();rownum++){  //to ignore heading we can ignore first row, so starts from 1
List<WebElement>cells= rows.get(rownum).findElements(By.tagName("td")) ;//corresponding cell content for each row

System.out.println("Total cols is" +cells.size());

//to get the content in all the cells in column

for(int colnum=0;colnum<cells.size();colnum++){
System.out.println(cells.get(colnum).getText() + "---");
}
System.out.println();// to get a new line
}
}

}

Retrive elements from Web Table

//when there is only one td or row value changing split the xpath into 2 and use for loop and get the values of the web table elements

String xpath_start="mnnn";
String xpath_end="hjjhjh";

for(int i=3;i<+33;i=i+2){
String x= driver.findElement(By.xpath(xpath_start+ i + xpath_end)).getText();
System.out.println(x);



Caleneder::

driver.get("http://www.spicejet.com");
driver.findElement(By.xpath("//*[@id='flightSearchContainer']/div[4]/button")).click();
driver.findElement(By.xpath("//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[3]/td[4]/a")).click();

//AJAX

//want to read all the values displayed when we type a letter in google search
Take the xpath of the first element displayed, observe the xpaths of all elements displayed
take xpath of textbox and send the keys(word)

then from the xpath of 1 st element, driver.findelement(by(xpatha).getText();

WebDriver driver= new FirefoxDriver();

driver.get("http://www.google.com");
driver.findElement(By.xpath("//*[@id='gs_tti0']")).sendKeys("b");
/* try{
int i=1;
while(true)
{
String val= driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr["+i+"]/td/div/table/tbody/tr/td[1]/span/b")).getText();// the first element displayed
System.out.println(val);
i++;
}


}catch(Exception e){
}}*/
}

Important urls

Handling Certificate errors

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.firefox.FirefoxProfile;

// to handle untrusted fire fox certificate errors
//create a firefox profile and accept the error in that profile manualy..
//if not manually, create firefox profile FirefoxProfile fp=new FirefoxProfile(); and fp.setAcceptuntrustedCertificates(true);
// or use the line fp.setAssumetrustedCertificateIssuer(false);
//chrome driver will take care of this certificate errors- when system proprty file executed
//for IE, u have to write line- driver.navigate().to("javascript:document.getElementById('overridelink').click()");

  1. driver.navigate().to("javascript:document.getElementById('overridelink').click()");  
//http://www.mythoughts.co.in/2012/05/handling-security-cerificatesuntrusteds.html#.U3E4ufldVmM

public class Certificate_Error {



public static void main(String[] args) {
FirefoxProfile fp= new FirefoxProfile();
fp.setAcceptUntrustedCertificates(true);
//or use below line
fp.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(fp);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://soapui-tutorial.com/login/soapui-memberlogin.php");
driver.findElement(By.xpath("xxxx")).sendKeys("aaa");
driver.findElement(By.xpath("xddd")).sendKeys("ccc");
driver.findElement(By.xpath("xxxx")).click();

Set<String> ids= driver.getWindowHandles();
Iterator <String> iter= ids.iterator();
String main=iter.next();
String tab= iter.next();
driver.switchTo().window(tab);
driver.findElement(By.xpath("xcdd")).click();

//Here comes the certificate error

handling tabs

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.chrome.ChromeDriver;


public class HDFC_tab2 {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "c:\\meeraja\\chromedriver.exe");

WebDriver driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("http://www.hdfc.com");

Set<String> winids= driver.getWindowHandles();  //set of strings

System.out.println(winids.size());
Iterator<String> iter= winids.iterator();
System.out.println(iter.next());
System.out.println("**************************");
//main
driver.findElement(By.xpath("//*[@id='acc-1-head-2']/a")).click();
driver.findElement(By.xpath("//*[@id='acc-1-section-2']/li[2]/a")).click();
System.out.println("**************************");
System.out.println("**************************");
winids= driver.getWindowHandles();  //set of strings

System.out.println(winids.size());
 iter= winids.iterator();
    String mainwinid= iter.next();
String tabwinid= iter.next();
System.out.println(mainwinid);
System.out.println(tabwinid);
driver.switchTo().window(tabwinid);

//driver.findElement(By.xpath("//*[@id='ic-news']")).click();
driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td/table/tbody/tr/td[3]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[2]/td/p[2]/a")).click();
System.out.println("**************************");
System.out.println("**************************");
System.out.println("**************************");
winids= driver.getWindowHandles();
System.out.println(winids.size());
iter= winids.iterator();
 mainwinid= iter.next();
tabwinid= iter.next();
String tabwinid2= iter.next();
System.out.println(mainwinid);
System.out.println(tabwinid);
System.out.println(tabwinid2);
driver.switchTo().window(tabwinid2);
driver.findElement(By.xpath("//*[@id='popup']/table/tbody/tr/td/table[2]/tbody/tr/td/table[1]/tbody/tr[4]/td/p/font/b/a")).click();

   driver.close();//close will only close the tab
//driver.exit will close all the tabs and window
driver.switchTo().window(mainwinid);
}

}

WebDriver4

Thread.sleep(4000) - will pause your programme..this will wait for 4000 sec, even though its ready withiin 2 sec we use wait..
 2 types of waits, implicit and Explicit

implicit wait is like global time, when ever the item is ready it will move to next step

driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);



Explicit is not global-but it is specific to an element-

WebDriverWait wait= new WebDriverWait(driver,20);

//wait for element to present
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("xxxx")));
//wait for element to disappear like loading icons
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("xxx")));

ExpectedCondition is an interface and ExpectedConditions is class that implements

Suppose for one element i want to wait 10 sec..for other i want 30 secs...we use FluentWait
wait for 30 secs, and if we wont found element dont throw exception, keep continue

new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);



SET Interface:
Set s= new HashSet();

list is an interface and array list is class implementing interface List
set has no duplicate elements
List has index and set has no index
no order
sets r used to manage d/f windows in selenium- when we 
click on a link and it opens new page/tab,selenium stores the new windows id a unique value for each in set

u need iterator retrieve an element in set
  

  
 List <String> l= new ArrayList<String>();
  l.add("meeraja");
  l.add("sri");
  l.add("san");
  l.add("kumar");
  System.out.println(l.size());
  System.out.println(l.get(2));
  
// .hasNext() - if next element present it returns true and if not it returns false.
//.next will move to next element
  
  Set<String> s= new HashSet<String>();
  s.add("India");
  s.add("America");
  s.add("london");
  s.add("India");
  s.add("India");
  System.out.println(s.size());
  Iterator<String> iter= s.iterator(); 

//u need iterator retrive element in set, there is no Get function

 System.out.println(iter.hasNext());
 System.out.println(iter.next());//
 System.out.println(iter.hasNext());
  
 while(iter.hasNext()){
 System.out.println(iter.next()); 
 }

TAB function:
//  Firefox profile has feature that the new tab opens as a new window
  //so, try in chrome
System.setProperty("Webdriver.chrome,driver", "c:\\meeraja\\chromedriver.exe");
  
  WebDriver driver= new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

webdriver3

WebDriver driver= null;
if(browser.equals("Firefox")){
driver= new FirefoxDriver();}
else if (browser.equals("Chrome")){
System.setProperty("webdriver.chrome.driver", "c:\\meeraja\\chromedriver.exe");
driver= new ChromeDriver();

Get the attribute value:

String x= driver.findElement(By.xpath("//*[@id='search-input']")).getAttribute("name");
System.out.println(x);
driver.findElement(By.xpath("//*[@id='search-input']")).sendKeys("meeraja");
System.out.println(x);
driver.findElement(By.xpath("//*[@id='search-input']")).clear();
}}

find Elements:  returns list of all link elements

List of all links in a web page:

WebDriver driver= new FirefoxDriver();
driver.get("http:\\www.yahoo.com");
//List<WebElement> list= new List()
List<WebElement> linklist=driver.findElements(By.tagName("a"));
System.out.println("total links  " +linklist.size());

WebElement link41= linklist.get(22);
System.out.println(link41.getText());

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


List all the web elements of fields..
List<WebElement> fields=driver.findElements(By.xpath("//input[@type='text']"));
fields.size();



//suppose in a outer box, there are 5 links, and user wants to click one by one.
//if we check the xpath the last part only changing, so make it 2 strings and add th enumber
//eg://*[@id='news_moreTopStories']/ul/li[1]/a
////*[@id='news_moreTopStories']/ul/li[2]/a

WebDriver driver= new FirefoxDriver();
driver.get("www.bbc.com");
String part1= "//*[@id='news_moreTopStories']/ul/li[";
String part2= "1]/a";

for(int i=1;i<5;i++){
String text= driver.findElement(By.xpath(part1+i+part2)).getText();
System.out.println(text);
driver.findElement(By.xpath(part1+i+part2)).click();
System.out.println(driver.getTitle());


Element present on page:

WebDriver driver= new FirefoxDriver();
driver.get("www.gmail.com");

int count=  driver.findElements(By.xpath("//*[@id='Email']")).size();
System.out.println(count);

function:  
public static boolean isElementPresent(String x_path) {
int k = driver.findElements(By.xpath(x_path)).size();
if(k == 0)
return false;
else

return true;

we can substitute in above code,,
int i=1;
while(isElementPresent(part1+i+part2)){
String text= driver.findElement(By.xpath(part1+i+part2)).getText();
System.out.println(text);
driver.findElement(By.xpath(part1+i+part2)).click();
System.out.println(driver.getTitle());
i++



Drop down list:


WebDriver driver= new FirefoxDriver();
driver.get("http://www.timesofindia.com");
WebElement droplist= driver.findElement(By.xpath("//select[@id='cityselection']"));
//xpath of dropdown
droplist.sendKeys("Goa");  //selected
List<WebElement> options =  droplist.findElements(By.tagName("option"));
//list all the elements with tag name as option
System.out.println("total options is " +options.size());
//no.of options in the dropdown

for(int i=0;i<options.size();i++)
{
//get the text of the option
System.out.println("options are  " + options.get(i).getText() + "...." +options.get(i).getAttribute("selected"));
//get the value true or null based on if it is selected or not..
}


Radio button:

WebDriver driver= new FirefoxDriver();
driver.get("http://www.echoecho.com/htmlforms10.htm");
List<WebElement> radio= driver.findElements(By.xpath("//input[@name='group1']"));//xpath of radio
System.out.println(radio.size());//no.of radio buttons
radio.get(0).click();//will click the first radio button


radio.get(0).getAttribute("checked"); //return true as it is selected
radio.get(1).getAttribute("checked");//
radio.get(2).getAttribute("checked");
radio.get(1).click();//now changing to 2nd radio
radio.get(0).getAttribute("checked");
radio.get(1).getAttribute("checked");//return true as it is selected
radio.get(2).getAttribute("checked");
}

Element visible or not:
WebDriver driver= new FirefoxDriver();
driver.get("http:\\www.yahoo.com");
//List<WebElement> list= new List()
List<WebElement> linklist=driver.findElements(By.tagName("a"));
System.out.println("total links  " +linklist.size());//get no.of links-tells element present or not

WebElement link41= linklist.get(42);//get the 42 rd link
System.out.println(link41.getText());//link text



for(int i=0; i<linklist.size();i++){
System.out.println(linklist.get(i).getText());//get the text of all links
System.out.println(linklist.get(i).isDisplayed());//element is displayed or not


Screenshot:

File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE) ;
FileUtils.copyFile(srcFile, new File("c:\\xxx.jpg"));

Good urls for selenium:

web driver2

open a browser and click on links:

FirefoxDriver driver= new FirefoxDriver();
driver.get("http://Gmail.com");
 driver.findElement(By.id("Email")).sendKeys("meerajaanasuri");
 driver.findElement(By.id("Passwd")).sendKeys("kUMAR$98");

 driver.findElementById("signIn").submit();

Xpath:

// means partial xpath
* any element on web page


//tag[@attr='value']
eg:  //*[@id='Email']
 //*[@id='Email' and name ='ddd']
//input[type='submit' and @class='ccgg']

get text:
String p= driver.findElement(By.xpath("html/body/div[1]/div[2]/div[1]/h2")).getText();

suppose there r 10 buttons have same class..
css class,look and feel be d;/f
By.className  or findelement (by.xpath("//input[@class='kkk']))


CSS selectors:
driver.findElement(By.cssSelector("input[id='Email']")).sendKeys("meeraja");

if it is some content which is in  a div class with a p paratag..
"div[class='hjhjhj'] p   //no slash just give some gap in css

if theres is id, simply
or By.cssSelector(" #Passwd")

or use symbols like ^ $ etc..

By.cssSelctor("input[name^='Emai')).sendkeys("startswith")
By.cssSelctor("input[name$='ail')).sendkeys("endswith")
By.cssSelctor("input[name*='mai')).sendkeys("contains")

Web driver1

documentation of selenium:
http://selenium.googlecode.com/git/docs/api/java/index.html

download webdriver jar files and configure in eclipse

Selenium we configure in eclipse..
Web driver is an interface in selenium tool api..
interface has lot of functions..

Firefox driver:

//FirefoxDriver dr1= new FirefoxDriver();

//sometimes firefox will have problmes with binaries in that case download binaries and use below code
//FirefoxBinary br= new FirefoxBinary("c:\\meeraja");
//FirefoxDriver dr1= new FirefoxDriver(br,null);


// To open a chrome driver,
System.setProperty("webdriver.chrome.driver", "c:\\meeraja\\chromedriver.exe");
ChromeDriver dr2= new ChromeDriver();

// To open a IE driver, System.setProperty("webdriver.ie.driver", "c:\\meeraja\\IEDriverServer.exe"); InternetExplorerDriver dr3= new InternetExplorerDriver();
sometime there is problem with protected mode, go ie tools, options and security select the same protection mode for all zones

Firefox Profiling: customize u r firefox browser accordingly..
file-exit in firefox.. in run, type firefox.exe -p profilemanager and create profile

use Ini class

ProfileIni prof= new ProfilesIni();
Firefox Profile p= prof.getProfile("Meeraja");
FirefoxDriver dr9= new FirefoxDriver(p);


driver.close() ; //will close firefox window
driver.quit() ; // close all ff windows associated with driver

Import documentation in Eclipse,
http://docs.seleniumhq.org/download/ right click on javadoc and copy the link addreess

http://selenium.googlecode.com/git/docs/api/java/index.html

go to java build path of your project and in under libraries , search for selenium -java 2.41.0.jar and expand and under javadoc location edit ,copy this file location, and at end of url plz remove index.html

http://selenium.googlecode.com/git/docs/api/java/ and click ok


Desired Capabilities:
DesiredCapabilities dc= new DesiredCapabilities(); dc.setJavascriptEnabled(true); FirefoxDriver fd= new FirefoxDriver(dc);
dc.setCapability (type ,value) //like to handle ssl certificate types and all..


Remote web driver: for grid we use, we use desired capabilities in remote web driver

proxy: is a class
proxy.setPrxyAutoconfigurl("url")
DesiredCapabilities dc= new DesiredCapabilities();
dc.setcapability(capailitytype.browsername,firefox)
dc.setcapability(capabilitytype.proxy,proxy)
FirefoxDriver fd= new FirefoxDriver(dc);
fd.get("http:\\google.com");

HTML Unit driver: u can emulate any type of browser version with this..
HtmlUnitDriver Hd= new HtmlUnitDriver(BrowserVersion.FIREFOX_17); Hd.get("http:\\google.com"); System.out.println(Hd.getTitle());

ANT5


ANT is build in compile tool. to run my program thro command prompt..
when code deployed on linux or unix and we can execute the prog using ANT
help run code independantly,
don't require  Eclipse

download and configure ANt and add build.xml file and chnge the class path parameters
change 4 properties jar file locattion and reports directory
in CMD, give commands like Ant, Ant complile,, ant run, ant clear etc..
usinf html report generation u will know which tests passed

Building bat file :

open cmd, open notepad
check the path of project whre build.xml lies
go to that place in cmd, ant clean and after that ant compile and then ant run..
now in notepad, just give the instruction as we just did and save as "Junit_samplebatfile.bat"
notepad content looks like:

c:
cd c:\WorkSpaces\Meeraja
ant clean compile run

save on desktop and when double click on it will autorun all cmds..


JUnit

Annotations

@Test
 write a test

@BeforeClass   will be called very begining of all functions
@AfterClass      will be called end of all functions

These aove 2 annotations should be Static in nature

@after

@Before  :  this fucntion will be called before calling each and every test
@After  :    this fucntion will be called after calling each and every test function

Order doesn't matter...where ever you write it will be executed in order


@Ignore  :  the function will be skip the execution

Assume.assumeTrue(false)  :  no test method (@Test)  will be called


Parameterize:
step1:
@RunWith(Parameterized.class)
Step2:

Initialise variables
Step3:
create Constructor

step4: function  @test

Step5: @Parameters
public static Collection<Object[]> getData(){
Object data[][]=new Object[2][2];
//1st row
data[0][0]= "xxx";
data[0][1]= 4566;
data[1][0]= "vv";
return Arrays.asList(data);//standard returning type


Assertions and error reporting:

Error Collector- declare this object as global
@Rule
public ErrorCollector errCol= new ErrorCollector();

try{
Assert.assertEquals("Hello", "Hello122");
Assert.assertTrue("error", 3>7);
}catch(Throwable t){
//System.out.println("error "+t);

//report error
errCol.addError(t);


Batch  test:  to run more than 1 at a time
use annotation,
@RunWith(Suite.class)
@SuiteClasses({
and then give all classes like xxx.class,xxx2.class,xxx3.class and run...