التخطي إلى المحتوى الرئيسي

Web Driver Locators and Command with Example

 

It is selenium component which is used to remotely connect application from a web browser. we can dynamically manage web elements of web applications using action and locators.
WebDriver provide set of command to perform the operation.
Webdriver can be executed in any web browser, Firefox, Chrome, Internet Explorer, etc.
WebDriver use programming language to write test script.
Top programming languages of Web Driver:-
1) JAVA 
2)C# 
3)Python
 4) Ruby etc
..............................................................................................................................

Step for Web Driver:-
1 Download eclipse software
    File --> new ---> Java Project
5 right-click on src package and create one class then check compilation and execution process.
6  right-click on the project and click on the build path option and add a selenium jar file
7  extract chromedriver.exe file and put into c: /
Some important command lists for web drivers?
1) get():-            this command is used to fetch the URL of a particular web page
2)  getTitle():-    this command is used to fetch the title of current web pages
3) sendKeys():-  It is used to write text on the text field
4) click():-          It is used to click the button
Locator:
It is used to find the path of UI elements using the name, id, CSS selector, class name, XPath, tag name, etc.
Webdriver provide different classes to manage UI element
driver.findElement(By.name("name of element"));
.....................................................................................................................................

Create Script to get the title of the Current Web Page?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Example1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
         WebDriver driver = new ChromeDriver();
         driver.get("http://newtours.demoaut.com/");
         String title = driver.getTitle();
         System.out.print(title);
         driver.close();
}
}
2)   Automation script to check that title is equal or not?
   public class WebDriverExampleFirst {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://eroomrent.in");
String s = driver.getTitle();
System.out.println("Title is "+s);
if(s.length()>60)
{
System.out.println("Title is Invalid");
}
else
{
System.out.println("Title is valid");
}

}

}



3 Create Automation Script to manage login and logout operation?


  public class LoginScript {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","c://chromedriver.exe");
/*WebDriver scs=null;
ChromeDriver ch = new ChromeDriver();
scs=ch;*/
WebDriver scs = new ChromeDriver();
scs.get("https://eroomrent.in/login.php");
scs.manage().window().maximize();
WebElement eleuser = scs.findElement(By.name("txtEmail"));
eleuser.sendKeys("gau100@gmail.com");
WebElement elepass = scs.findElement(By.name("txtPassword"));
elepass.sendKeys("Gaurav@12345");
scs.findElement(By.name("btnsubmit")).click();
Actions actions = new Actions(scs);
WebElement mainMenu = scs.findElement(By.partialLinkText("Dashboard"));
actions.moveToElement(mainMenu);
actions.build().perform();
         scs.findElement(By.linkText("Logout")).click();
}

}


Another Automation Script Example to Implement Integration Testing using Login----> Dashboard Form-----> Logout

 package basicexample;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class LoginScript {
public static void main(String args[])
{
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com/ims/");
WebElement ele = driver.findElement(By.name("email"));
ele.sendKeys("nitinscs@gmail.com");
WebElement ele1 = driver.findElement(By.name("pass"));
ele1.sendKeys("12345");
WebElement ele2 = driver.findElement(By.name("submit"));
ele2.click();
driver.manage().window().maximize();
WebElement ele3 = driver.findElement(By.name("txtname"));
ele3.sendKeys("nitin mahajan");
WebElement ele4 = driver.findElement(By.name("txtlist"));
ele4.sendKeys("testing purpose");
Select s = new Select(driver.findElement(By.name("branch")));
s.selectByIndex(1);
WebElement ele5 = driver.findElement(By.name("btnsubmit"));
ele5.click();
driver.switchTo().alert().accept();

}

}

Assignments:-

     
Q1) Create Test Script to check the login of Facebook?

Q2)  Create an account for a Facebook web page?

Q3)  Create Automation Script for Contact us page?


Solution:-

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class WebDriverExample3 {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com/contact-us/index.html");
WebElement elename = driver.findElement(By.name("text-903"));
elename.sendKeys("Vivek soni");
WebElement elemobile = driver.findElement(By.name("tel-944"));
elemobile.sendKeys("1234567891");
WebElement eleemail = driver.findElement(By.name("email-712"));
eleemail.sendKeys("abcd@gmail.com");
Select course = new Select(driver.findElement(By.name("Course")));
course.selectByIndex(2);
WebElement elemessage = driver.findElement(By.name("textarea-80"));
elemessage.sendKeys("testing purpose");
WebElement btnclcik = driver.findElement(By.name("btnsubmit"));
btnclcik.click();




}

}



Locator of Web Driver:-

It is used to locate elements using different Web Element Attribute.

1) Locate By name:-

      <input type="text" name="t"   />

       By.name("t")

      WebElement eleref = driver.findElement(By.name("t"));


2) Locate by Id:-

   if the element name is not present or the name is duplicate then we prefer another attribute id.
   
   <input type="text" id="t"  />

    By.id("Id of element")
    WebElement eleref = driver.findElement(By.id("t"));
   


3) Locate Hyperlink or anchor or menu item:-

     It is used to perform navigation to click on hyperlink text:-

     <a href="http://google.com">google</a>
     
      By.linkText("google")
        
     <a href="http://google.com">click to google</a>

      By.linkText("click to google")

     By.partialLinkText("click")


   

Example of Locator's:-
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CheckLocator {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com/test.html");
WebElement eleid = driver.findElement(By.id("txt1"));
eleid.sendKeys("Manish Sharma");
WebElement elename = driver.findElement(By.name("txt2"));
elename.sendKeys("Ravi kumar");
//WebElement eleclick = driver.findElement(By.linkText("Click"));
//eleclick.click();
//WebElement ele2= driver.findElement(By.linkText("Click to shivaconcept"));
//ele2.click();
WebElement ele2= driver.findElement(By.partialLinkText("shivaconcept"));
ele2.click();

}

}


4) Locate  By class name:-

if the element has no name, id then we use the Classname locator to locate the element.

<input  type="text" class="abc"   />


Syntax of Class name locator

WebElement classname = driver.findElement(By.className("abc"));
classname.sendKeys("Class name");


5) Locate By CSS Selector:-

It is used to locate elements using CSS (cascading style sheet) , CSS is mostly used to implement designing.

   5.1) By Tagname and id
   
      WebElement ele = driver.findElement(By.cssSelector(Tagname#id));

   
<input type="text" id="txt"   />

  <p id="txt"  />

    WebElement ele = driver.findElement(By.cssSelector("input#txt"));
    WebElement ele = driver.findElement(By.cssSelector("p#txt"));

 

   5.2) By  Tag and Attribute name:-

        If the Html element does not contain id, name,class name then we can use Attribute name as a locator.

       <input type="text" value="click"   />
      WebElement ele = driver.findElement(By.cssSelector("tagname[attributename=value]"));
       WebElement ele = driver.findElement(By.cssSelector("input[value=click]"));

5.3) By  Tag, Classname, and Attribute name:-

        It the Html element does not contain id, name, and same class name in multiple Html elements then we can use Tag, Attribute and class as a locator.
       <p class="a" />
      <p class="b" />
       <input type="text" value="click"  class="a"  />
      <input type="text" value="click"  class="b"   />

 
      WebElement ele = driver.findElement(By.cssSelector("tagname.classname[attributename=value]"));
       WebElement ele = driver.findElement(By.cssSelector("input.a[value=click]"));






 
Complete Code of Locator:

public class CheckLocator {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com/test.html");
WebElement eleid = driver.findElement(By.id("txt1"));
eleid.sendKeys("Manish Sharma");
WebElement elename = driver.findElement(By.name("txt2"));
elename.sendKeys("Ravi kumar");
//WebElement classname = driver.findElement(By.className("abc"));
//classname.sendKeys("Class name");
//WebElement cssloc = driver.findElement(By.cssSelector("input#b"));
//cssloc.sendKeys("Find Element By Id");
//WebElement cssbytagattr = driver.findElement(By.cssSelector("input[value=click]"));

//cssbytagattr.sendKeys("Find Element By Tag and Attribute");
 
        WebElement cssbytagattr = driver.findElement(By.cssSelector("input.abc[value=hello]"));

cssbytagattr.sendKeys("Find Element By Classname, Tag and Attribute");
//WebElement eleclick = driver.findElement(By.linkText("Click"));
//eleclick.click();
//WebElement ele2= driver.findElement(By.linkText("Click to shivaconcept"));
//ele2.click();
// WebElement ele2= driver.findElement(By.partialLinkText("shivaconcept"));
// ele2.click();

}

}




4) Find By Tag name:-

  if we want to access <p>,<h1>,<h2> ,<b>,<i>,<li>,
<div>  these HTML element then we can use By.tagName("p")


Code for Tag name:-

WebElement ele4 = driver.findElement(By.tagName("p"));
String s = ele4.getText();



Q CREATE AUTOMATION SCRIPT to DISPLAY ALL PARAGRAPH TEXT USING SELENIUM WEB DRIVER?


import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverExampleForTagName {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com/test.html");
List<WebElement> lst = driver.findElements(By.tagName("p"));

for(WebElement o:lst)
{
System.out.println(o.getText());
}


}

}


Q) Create Automation Script to Count Total Number of Hyperlinks in Web Pages, Title of Hyperlink and URL?


import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverCountHyperlink {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://shivaconceptsolution.com");
List<WebElement> lst = driver.findElements(By.tagName("a"));
System.out.println(lst.size());
for(WebElement we:lst)
{
System.out.println(we.getText()+""+we.getAttribute("href"));
}

}

}

   Q) Create Automation Script to Count Total Number of  Images?

package scs;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CountImageScript {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("http://shivaconceptsolution.com/test.html");
  driver.manage().window().maximize();
  List<WebElement> lst = driver.findElements(By.tagName("img"));
  System.out.print("Total Images are"+lst.size());
  

}

}



ASSIGNMENT:-

Create an Automation script to count the total text field in the contact us page of shivaconceptsolution?

Create An Automation Script to find max-width, the height of images?

Create An Automation Script to find max weight of images and display name of that images?





4) By Xpath:-


Xpath means XML path ,it provides a complete path from HTML top section to current Html element.

It consumes more time to find elements and if we add an element to the web page then XPath will be incorrect.

hence we did not prefer XPATH as a locator but if we have no option to find the element then we can use XPATH.


now XPath has been modified based on two different subpath

1) Absolute Xpath:-

  it is a normal XPath that provides a complete path from starting element to the current element.


<html>

<head>

<body>

<div id="conatiner">

<p>Hello</p>

</div>
</body>
</html>

xpath = //html/body/div/p

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.internal.WebElementToJsonConverter;

public class XpathExample {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","c:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://shivaconceptsolution.com/test.html");
        WebElement we = driver.findElement(By.xpath("//html/body/input[11]"));
        we.click();

}

}

2) Relative Xpath:-

 it is a new implementation of XPath which is used to co-relate the container element and prepare the path.

xpath= //tagname[@attributename=value]


xpath= //div[@id='id']/p

xpath=//*[@id='id']

xpath=//*[@classname='classname']


public class XpathExample {

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","c:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://efixman.com//customer/login");
        WebElement we = driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div[2]/input"));
        we.sendKeys("abcd@gmail.com");

}

}



1) Example of Complete Locator of ShivaConceptSolution.com/test.html


package scs;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class LocatorExampleInWebDriver {

public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("http://shivaconceptsolution.com/test.html");
  driver.manage().window().maximize();
/*  driver.findElement(By.id("txt1")).sendKeys("Sumit"); 
  driver.findElement(By.id("txt2")).sendKeys("123456789");
  driver.findElement(By.id("txt3")).sendKeys("sumitrawat@12345");
  driver.findElement(By.xpath("(//input[@id=\"txt3\"])[2]")).click(); */
  driver.findElement(By.xpath("(//input[@id=\"txt3\"])[2]")).clear();
  driver.findElement(By.xpath("(//input[@id=\"txt3\"])[2]")).sendKeys("03-06-2021");
  driver.findElement(By.id("txt4")).sendKeys("9988776655"); 
  Select s = new Select(driver.findElement(By.name("c[]")));
  s.selectByIndex(1);
  s.selectByIndex(3);
  Select s1 = new Select(driver.findElement(By.id("c")));
  s1.selectByIndex(3);
  driver.findElement(By.name("chk1")).click();
  driver.findElement(By.name("chk2")).click();
  driver.findElement(By.name("chk2")).click();
// driver.findElement(By.linkText("Click")).click();
         // driver.findElement(By.partialLinkText(" shivaconcept")).click();
         // driver.navigate().back();
//  driver.findElement(By.linkText("Click")).click();
// driver.navigate().back();
//  driver.findElement(By.className("abc")).sendKeys("test classname");;
//  driver.findElement(By.cssSelector("input#b")).sendKeys("test by id and tagname");
//  driver.findElement(By.cssSelector("input[value=hello]")).clear(); 
         //  driver.findElement(By.cssSelector("input[value=hello]")).sendKeys("ssssssssssss"); 
  //driver.findElement(By.cssSelector("input.abc")).sendKeys("tagname and  classname");;
}

}








تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...