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

Thursday, 21 May 2015

Exceptions in Selenium webdriver:

Exceptions in Selenium webdriver:

exception selenium.common.exceptions.ElementNotSelectableException:
Thrown when trying to select an unselectable element.

For example, selecting a ‘script’ element.

exception selenium.common.exceptions.ElementNotVisibleException:
Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with.

Most commonly encountered when trying to click or read text of an element that is hidden from view.

exception selenium.common.exceptions.ErrorInResponseException
Thrown when an error has occurred on the server side.

This may happen when communicating with the firefox extension or the remote driver server.

exception selenium.common.exceptions.ImeActivationFailedException
Thrown when activating an IME engine has failed.

exception selenium.common.exceptions.ImeNotAvailableException:
Thrown when IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.

exception selenium.common.exceptions.InvalidCookieDomainException:
Thrown when attempting to add a cookie under a different domain than the current URL.

exception selenium.common.exceptions.InvalidElementStateException:
exception selenium.common.exceptions.InvalidSelectorException:
Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression and it is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).

exception selenium.common.exceptions.InvalidSwitchToTargetException:
Thrown when frame or window target to be switched doesn’t exist.

exception selenium.common.exceptions.MoveTargetOutOfBoundsException:
Thrown when the target provided to the ActionsChains move() method is invalid, i.e. out of document.

exception selenium.common.exceptions.NoAlertPresentException:
Thrown when switching to no presented alert.

This can be caused by calling an operation on the Alert() class when an alert is not yet on the screen.

exception selenium.common.exceptions.NoSuchAttributeException:
Thrown when the attribute of element could not be found.

You may want to check if the attribute exists in the particular browser you are testing against. Some browsers may have different property names for the same property. (IE8’s .innerText vs. Firefox .textContent)

exception selenium.common.exceptions.NoSuchElementException:
Thrown when element could not be found.

If you encounter this exception, you may want to check the following:
Check your selector used in your find_by...
Element may not yet be on the screen at the time of the find operation,
(webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait() for how to write a wait wrapper to wait for an element to appear.

exception selenium.common.exceptions.NoSuchFrameException:
Thrown when frame target to be switched doesn’t exist.

exception selenium.common.exceptions.NoSuchWindowException:
Thrown when window target to be switched doesn’t exist.

To find the current set of active window handles, you can get a list of the active window handles in the following way:

print driver.window_handles
exception selenium.common.exceptions.RemoteDriverServerException:
exception selenium.common.exceptions.StaleElementReferenceException:
Thrown when a reference to an element is now “stale”.

Stale means the element no longer appears on the DOM of the page.

Possible causes of StaleElementReferenceException include, but not limited to:
You are no longer on the same page, or the page may have refreshed since the element
was located. * The element may have been removed and re-added to the screen, since it was located. Such as an element being relocated. This can happen typically with a javascript framework when values are updated and the node is rebuilt. * Element may have been inside an iframe or another context which was refreshed.

exception selenium.common.exceptions.TimeoutException:
Thrown when a command does not complete in enough time.

exception selenium.common.exceptions.UnableToSetCookieException:
Thrown when a driver fails to set a cookie.

exception selenium.common.exceptions.UnexpectedAlertPresentException:
Thrown when an unexpected alert is appeared.

Usually raised when when an expected modal is blocking webdriver form executing any more commands.

exception selenium.common.exceptions.UnexpectedTagNameException:
Thrown when a support class did not get an expected web element:
Base webdriver exception.

Monday, 18 May 2015

Keyboard interactions and Mouse interactions in Selenium Web Deiver.

The Advanced User Interactions API is a new, more comprehensive API for describing actions a user can perform on a web page. This includes actions such as drag and drop or clicking multiple elements while holding down the Control key.
For Example...

    /**
     * for press Enter
     */
    public void  enter()
    {
        Actions act=new Actions(Driver.driver);
        act.sendKeys(Keys.ENTER).perform();
    }

    /**
     * for save
     */
    public void  save()
    {
        Actions act=new Actions(Driver.driver);
       
        act.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0073')).perform();
    }

    /**
     * for Paste
     */
    public void  paste()
    {
       
       
        Actions act=new Actions(Driver.driver);
        act.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0076')).perform();
    }

    /**
     *  for Cut
     */
    public void  cut()
    {
       
        Actions act=new Actions(Driver.driver);
        act.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0078')).perform();
    }

    /**
     * For Right click
     * @param wb
     */
    public void  rightClickOnwebElement(WebElement wb)
    {
       
        Actions act=new Actions(Driver.driver);
        act.contextClick(wb).perform();
    }

        /**
         * For Drag And Drop
         * @param srcwb
         * @param dstwb
         */
        public void  dragAndDrop(WebElement srcwb,WebElement dstwb)
        {
           
            Actions act=new Actions(Driver.driver);
            act.dragAndDrop(srcwb, dstwb).perform();
        }

        /**
         * Double click
         */
        public void  doubleClick()
        {
           
            Actions act=new Actions(Driver.driver);
            act.doubleClick().perform();
        }
   

Tuesday, 21 April 2015

How to connect Excel Sheet Using Selenium Web driver.

To get data from excel sheet or write data in excel sheet we require some other  api which available  on below link:
Steps :
1. Download apache poi form https://poi.apache.org/download.html link.
2. Unzip and import jar your project.
3.Use given API to connect to excel sheet



package genricLib;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;



import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;


public class ExcelLib {
String path="C:\\Users\\ADMIN\\Desktop\\EmployeeDetails.xls";
/**
* Get Data From Excel File.....
* @param sheet
* @param rowno
* @param colno
* @return data
*/
public String getData(String sheet,int rowno,int colno) throws InvalidFormatException, IOException {

FileInputStream fis=new FileInputStream(path);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheet);
Row rw=sh.getRow(rowno);
String data=rw.getCell(colno).getStringCellValue();


return data;
}
/**
* Save data in Excel Sheet
* @param sheet Name
* @param rowno
* @param colno
* @param data
*/
public void setData(String sheet,int rowno,int colno,String data) throws InvalidFormatException, IOException {

FileInputStream fis=new FileInputStream(path);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheet);
Row rw=sh.getRow(rowno);
Cell cel=rw.getCell(colno);
cel.setCellType(cel.CELL_TYPE_STRING);
cel.setCellValue(data);
FileOutputStream fos=new FileOutputStream("C:\\Documents and Settings\\PavanD\\Desktop\\pardeep.xlsx");
wb.write(fos);




}
/**
* To get Total no row in Excel File
* @param sheet
* @return No of Row
*/

public int getRowCount(String sheet) throws InvalidFormatException, IOException
{

FileInputStream fis=new FileInputStream(path);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheet);
int data=sh.getLastRowNum();

return data;
}
/**
* To Get Total No Of Column in Row
* @param sheet
* @param rowNo
*/
public int getColomnCount(String sheet,int rowNo) throws InvalidFormatException, IOException
{

FileInputStream fis=new FileInputStream(path);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheet);
Row rw=sh.getRow(rowNo);
int data=rw.getLastCellNum();

return data;

}

}

Thursday, 16 April 2015

How to take ScreenShot using Selenium WebDriver.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class ReportLib {


/**
* To Get Screen Shot If Test case Fail and 
* @throws IOException
*/
public void getsnapShot(String name) throws IOException{
String path="E:\\abc\\xyz\\project1\\TestData\\"+name+".png";

EventFiringWebDriver edriver=new  EventFiringWebDriver(Driver.driver);
File srcimg=edriver.getScreenshotAs(OutputType.FILE);
File dstimg=new File(path);
FileUtils.copyFileToDirectory(srcimg, dstimg);

}

}
For Example:

Wednesday, 15 April 2015

How to Handle Proxy Setting using Selenium Webdriver .

Mozilla FireFox:
FirefoxProfile profile = new FirefoxProfile();

profile.setPreference("network.proxy.type", 1);

profile.setPreference("network.proxy.http", "localhost");

profile.setPreference("network.proxy.http_port", 3128);

WebDriver driver = new FirefoxDriver(profile);

or
String PROXY = "localhost:8080";

org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
     .setFtpProxy(PROXY)
     .setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);

 Internet Explorer:

String PROXY = "localhost:8080";

org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
     .setFtpProxy(PROXY)
     .setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);

WebDriver driver = new InternetExplorerDriver(cap);

Chrome:
String PROXY = "localhost:8080";

org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
     .setFtpProxy(PROXY)
     .setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);

WebDriver driver = new ChromeDriver(cap);

Thursday, 9 April 2015

How to Interact with hidden elements using Selenium Webdriver.

Since a user cannot read text in a hidden element, WebDriver will not allow access

to it as well.However, it is possible to use Javascript execution abilities to call getText directly

from the element:

WebElement element =((JavascriptExecutor) driver).executeScript("return arguments[0].getText();", element);

Wednesday, 8 April 2015

How to handle SSL certificate in Mozilla,Chrome and Internet Explorer or How to work with Https websites .

Mozilla:

FirefoxProfile profile = new FirefoxProfile();

profile.setAssumeUntrustedCertificateIssuer(false);

driver = new FirefoxDriver(profile);

driver.get("https://google.com/ <https://mailbox.com/> ");


Chrome:

DesiredCapabilities capabilities = new DesiredCapabilities();

    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

    System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\Selenium 

softwares\\drivers\\chromedriver.exe");

    _driver = new ChromeDriver(capabilities);

    System.setProperty("webdriver.chrome.driver",

            "D:/Softwares/Selenium softwares/drivers/chromedriver.exe");

    //_driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);

Internet Explorer :

System.setProperty("webdriver.ie.driver",

    "D:/Softwares/Selenium softwares/drivers/IEDriverServer.exe");

    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();    

capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_B

Y_IGNORING_SECURITY_DOMAINS, true); 

    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

    capabilities.setJavascriptEnabled(true); 

    //capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-

certificate-errors"));

    _driver = new InternetExplorerDriver(capabilities);

    _driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);


    login();

    

Wait Statement in Selenium Webdriver.

Wait Statement during Navigation:



Thread.sleep(5000) Wait For 5 Seconds using Java API

Implicitly Wait Command:Implicit wait statement used wait till entire page get download
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);


Expected Conditions Commands:Explicit wait statement used to load web element not entire page used in dynamic app(ajax app)

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

FluentWait Command:An implementation of the Wait interface that may have its timeout and polling interval configured on the fly. Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page

->:Waiting 30 seconds for an element to be present on the page, checking
->: for its presence once every 5 seconds.
  
  Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }

   });

Set ScriptTimeoutSet the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.

driver.manage().timeouts().setScriptTimeout(100,SECONDS);
PageLoadTimeout:Set the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.


driver.manage().timeouts().pageLoadTimeout(100, SECONDS);

Tuesday, 7 April 2015

How to connect Data Base Using Using Java or Selenium Webdriver

Data Base Code

import java.sql.*;

public class DatabaseConnectDemo{

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

//Resgister the driver through 

Class.forName("oracle.jdbc.driver.OracleDriver");

System.out.println("registered driver successfully");

//Create the connection and assign to connection reference

Connection 

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", 

"username", "password");

System.out.println("connection successsfully");

//create a statement through connection reference and assign to statement reference

Statement stmt=con.createStatement();

System.out.println("statement object created successfully");

//call the executequery method through statement reference and pass the query as 

argument.

ResultSet rs=stmt.executeQuery("select * from emp");

System.out.println("query is executed");

while(rs.next()){

int i=rs.getInt(1);

String str=rs.getString(2);

String str1=rs.getString(3);

int i1=rs.getInt(4);

System.out.println(i+"\t"+str+"\t"+str1+"\t"+i1);

}}}

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);


}


}



Translate

Popular Posts

Total Pageviews