Planet Jaspersoft

Filter by tags:

May 28, 2020

Hi, in this post, we will learn about how to auto compare the displayed drop down select values to the user expected drop down values.

i.e , compare "actual values displayed" to the "user expected values"  for the drop down select for a web data table.

Zoom-In by tapping the image:

The approach is as follows: 
1) Declare a list for user expected values of an integer(later in the code convert to sting)
     or String type.
2) Locate the drop down select element on the web using xpath locator technique.
3) Create an object of "Select" class with the argument of  drop down select element. (from #2)
4) Store the values of actual values displayed in another list of type WebElement
5) Compare the two lists  and confirm the equality.

user expected values
List<Integer> expectedDropDownValues = new ArrayList<Integer>()
{
{
add
(10);
add
(25);
add
(50);
add
(100);
}
};

actual values displayed
WebElement entriesDropDownLocator = driver.findElement(By.xpath("//select[@name='example_length']"));

Select entriesDropDown = new Select(entriesDropDownLocator);

List
<WebElement> actualDropDownValues = entriesDropDown.getOptions();

Compare the two lists
for(int i=0;i<actualDropDownValues.size();i++) {

if(actualDropDownValues.get(i).getText().equals(expectedDropDownValues.get(i).toString())) {

System
.out.println("Value Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
}else {
System
.out.println("Value Not Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
}
}

CompareDisplayedDropdownSelectValuesWithActualValues.java
package selenium.datatables;

import java.util.ArrayList;
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;
import org.openqa.selenium.support.ui.Select;


public class CompareDisplayedDropdownSelectValuesWithActualValues {

public static WebDriver driver;

public void compareDispalyedRowCountToActualRowCount() throws Exception {

@SuppressWarnings("serial")
List<Integer> expectedDropDownValues = new ArrayList<Integer>()
{
{
add(10);
add(25);
add(50);
add(100);
}
         };

System.out.println("Expected dropdown values for accounts table");

for (Integer expectedOptions : expectedDropDownValues) {
System.out.println(expectedOptions.toString());
}

WebElement entriesDropDownLocator = driver.findElement(By.xpath("//select[@name='example_length']"));

Select entriesDropDown = new Select(entriesDropDownLocator);
List<WebElement> actualDropDownValues = entriesDropDown.getOptions();

System.out.println("Actual dropdown values from accounts table");
for (WebElement actualValues : actualDropDownValues) {
System.out.println(actualValues.getText());
}
System.out.println("Compare the actual values with the expected values for dropdown");

for(int i=0;i<actualDropDownValues.size();i++) {

if(actualDropDownValues.get(i).getText().equals(expectedDropDownValues.get(i).toString())) {

System.out.println("Value Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
}else {
System.out.println("Value Not Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
}
}
}

public void closeDriver() {
driver.close();
}
public void quitDriver() {
driver.quit();
}

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

CompareDisplayedDropdownSelectValuesWithActualValues c = new CompareDisplayedDropdownSelectValuesWithActualValues();

System.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput","true" );

driver = new ChromeDriver();
driver.get("https://datatables.net/examples/basic_init/zero_configuration.html");
driver.manage().window().maximize();
c.compareDispalyedRowCountToActualRowCount();

c.closeDriver();
c.quitDriver();
}
}

Console Log:
Expected dropdown values for accounts table
10
25
50
100
Actual dropdown values from accounts table
10
25
50
100
Compare the actual values with the expected values for dropdown
Value Matching :Actual List Value=10 And Expected Value=10
Value Matching :Actual List Value=25 And Expected Value=25
Value Matching :Actual List Value=50 And Expected Value=50
Value Matching :Actual List Value=100 And Expected Value=100

I hope you find this post is useful, stay tuned for more automation.!

May 28, 2020

Hi , In this tutorial, we'll learn about how to compare displayed row count on page is equals to data table row count in java selenium.

There are several ways to accomplish this, by the time I write this article, I've come across two ways.
They are
1) Calculate the no. of rows in data table by navigating through the pagination buttons.
2) Calculate the no. of rows in data table by using jQuery "length" function.

We will see the latter implementation in this post.

Tap on to the image to get better visibility of content : 

The approach is as follows.
1. Wait for sometime to load the page for which data table is present.
2. Take an integer variable say "dataTableActualRowCount" with 0 as the default value.
3. Create  JavascriptExecutor object for the driver.
4. Use jQuery "length" function technique within java-selenium code.
5. jQuery stores the value in Object so convert it into integer and store the jquery returned length in
     dataTableActualRowCount
6. Find the displayed count from bottom of the page using WebElement finder technique and store it
    in another integer variable say "displayedCountOfRowsOnPage".
7. Now, Compare the values of "dataTableActualRowCount" and
      "displayedCountOfRowsOnPage".
8. If dataTableActualRowCount == displayedCountOfRowsOnPage then "displayed row count
   on page is equals to data table row count " else "displayed row count on page is NOT equals
   to data  table row count".

dataTableActualRowCount - calculating using jQuery "length" function
int dataTableActualRowCount=0;

JavascriptExecutor js
=(JavascriptExecutor)driver;

dataTableActualRowCount
= ((Number)js.executeScript("return $('#example').DataTable().rows().data().toArray().length;")).intValue();

System
.out.println("Data table row count="+dataTableActualRowCount);

displayedCountOfRowsOnPage - finding through WebElement
String displayedCount = driver.findElement(By.id("example_info")).getText().split(" ")[5];

int displayedCountOfRowsOnPage = Integer.parseInt(displayedCount);

System
.out.println("Data table display count on page ="+displayedCountOfRowsOnPage);

CompareDisplayedRowCountToDataTableRowCount.java
package selenium.datatables;


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

public class CompareDisplayedRowCountToDataTableRowCount {

public static WebDriver driver;
public static void main(String[] args) throws Exception {

System.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput","true" );

driver = new ChromeDriver();
driver.get("https://datatables.net/examples/basic_init/zero_configuration.html");
driver.manage().window().maximize();
compareDispalyedRowCountToActualRowCount();
}


public static void compareDispalyedRowCountToActualRowCount() throws Exception {
Thread.sleep(10000);

int dataTableActualRowCount=0;

JavascriptExecutor js=(JavascriptExecutor)driver;

dataTableActualRowCount = ((Number)js.executeScript("return $('#example').DataTable().rows().data().toArray().length;")).intValue();
System.out.println("Data table row count="+dataTableActualRowCount);

String displayedCount = driver.findElement(By.id("example_info")).getText().split(" ")[5];

int displayedCountOfRowsOnPage = Integer.parseInt(displayedCount);
System.out.println("Data table display count on page ="+displayedCountOfRowsOnPage);

if(Integer.compare(dataTableActualRowCount, displayedCountOfRowsOnPage)==0) {
System.out.println("Displayed count on page is equals to the data table row count ");
}else {
System.out.println("Displayed count on page is NOT equals to the data table row count");
throw new Exception("Displayed count on page is NOT equals to the data table row count");
}
}
}


I hope you find this tutorial is useful, stay tuned for more automation.!

- Sadakar Pochampalli

May 28, 2020

May 26, 2020

Hi, in this post, we will walk through the usage and live example of isEnabled() method. isEnabled() method, we apply in special scenarios where in we select a check box and get the status of a button i.e., enabled or disabled. Let's take a look into the following example.

isEnabled()
  • To verify if an element is enabled or disabled on web-page. 
  • Returns "ture" if element is enabled and returns "false" if an element is disabled. 
  • Examples: Mostly used with button elements, locked/disabled text input elements.
Problem Statement : 
Display the status of "Sign up" button - The below two images gives an idea on how the button looks before enabled and after enabled after selecting a check box.

Sign up  button before enabled i.e., before selecting check box "I have read...." 
Tap on the image to get better visibility:
Sign up  button after enabled i.e., after selecting check box "I have read...." 
Tap on the image to get better visibility:
The below piece of selenium script does
    a) verifies the status of "Sign up" button before enabled.
    b) selects the check box "I have read..." and
    c)  verifies the status of "Sign up" button after selecting the  check box.

//isEnabled() example - before selecting the check box
//display the enable or disable status of "Sign Up" button before selecting the check box
WebElement signUp
= driver.findElement(By.xpath("//button[@id='signup']"));
boolean b1 = signUp.isEnabled();//false
System
.out.println("Sign Up button enable/disable before selecting \"I have read and accpet...\" check box = "+b1);


//select the "I have read and accept check box
WebElement element
=driver.findElement(By.xpath("//input[@id='termsAndPrivacy']"));
WebDriverWait wait
= new WebDriverWait(driver, 60);
wait
.until(ExpectedConditions.visibilityOf(element));
new Actions(driver).moveToElement(element, 1, 1).click().perform();

//isEnabled() example - check box
//display the enable or disable status of "Sign Up" button after selecting the check box
boolean b2 = signUp.isEnabled();//true
System
.out.println("Sign Up button enable/disable after selecting \"I have read and accpet...\" check box = "+b2);

Watch this ~ 6 min video tutorial for the demo : 


WebElementInterfaceMethod_isEnabledDemo.java
package selenium.webelement.methods;

/* button isEnabled() demo */

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.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebElementInterfaceMethod_isEnabledDemo {

public static void main(String[] args) {

WebDriver driver;

//loading Chrome driver from physical drive
System.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");

System.setProperty("webdriver.chrome.silentOutput", "true");
//System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

//launch the browser
driver = new ChromeDriver();

//navigate to site
driver.navigate().to("https://us.megabus.com/account-management/login");

//maximize the browser
driver.manage().window().maximize();

//close the message on site
driver.findElement(By.xpath("//i[@class='close mb-close']")).click();

// Sign Up form
WebElement signUpFromTab = driver.findElement(By.xpath("//a[@class='btn btn-link btn-block'][contains(text(),'Sign up')]"));
signUpFromTab.click();

//Email
WebElement email = driver.findElement(By.xpath("//input[@id='email']"));
email.sendKeys("java.selenium2023@gmail.com");

//Confirm Email
WebElement confirmEmail = driver.findElement(By.xpath("//input[@id='confirmEmail']"));
confirmEmail.sendKeys("java.selenium2023@gmail.com");

//Choose a Password
WebElement chooseAPassword = driver.findElement(By.xpath("//input[@id='choosePassword']"));
chooseAPassword.sendKeys("JavaSelenium2023");

//Confirm Password
WebElement confirmPassword = driver.findElement(By.xpath("//input[@id='confirmPassword']"));
confirmPassword.sendKeys("JavaSelenium2023");

//isEnabled() example - before selecting the check box
//display the enable or disable status of "Sign Up" button before selecting the check box
WebElement signUp = driver.findElement(By.xpath("//button[@id='signup']"));
boolean b1 = signUp.isEnabled();
System.out.println("Sign Up button enable/disable before selecting \"I have read and accpet...\" check box = "+b1);


//select the "I have read and accept check box
WebElement element=driver.findElement(By.xpath("//input[@id='termsAndPrivacy']"));
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(element));
new Actions(driver).moveToElement(element, 1, 1).click().perform();

//isEnabled() example - check box
//display the enable or disable status of "Sign Up" button after selecting the check box
boolean b2 = signUp.isEnabled();
System.out.println("Sign Up button enable/disable after selecting \"I have read and accpet...\" check box = "+b2);

signUp.click();

//close the browser
//driver.close();

//close all the browsers opened by WebDriver during execution and quit the session
//driver.quit();
}
}


To know more about isDisplayed() or isSelected() methods, please visit this post @

WebElement interface methods examples in selenium - part 2 | Understanding of methods isDisplayed() Vs isEnabled() Vs isSelected()


isDisplayed()
  • To verify presence of a web-element with in the web page. 
  • This method returns either true or false boolean values. 
  • If the element is present it returns "true" otherwise it returns "false". 
  • This method avoids the problem of having to parse an element's "style" attribute.
  • Example : This method can be applicable for all the elements on web-page. 
 isSelected()
  • Returns whether an element say check box or radio button is selected or not. 
  • If selected returns "true", if not selected returns "false". 
  • Examples: Check boxes, drop downs , radio buttons 
I hope this helps someone in the community, stay tuned for more automation.

    May 26, 2020

    May 23, 2020

    Hi, in this page, we will discuss about Actions(class) and Action(interface) and keyboard events example in selenium with some key take away notes.

    For, mouse events tutorial, click this link.



    Actions

    • It is a class and the package is org.openqa.selenium.interactions.Actions
    • It represents collection of individual Action that you want to perform.
    • Using this class we can handle keyboard and mouse events. i.e., 
      • Keyboard interface methods 
      • Mouse interface methods 

    Action 

    • Action is an interface 
    • It represents single user interaction. 
    • Using this interface, on the Actions object we perform series of actions. 
    • Most widely and must use method is perform() after creating series of actions and storing in Action   

    Keyboard events examples 

    keyDown --> for instance, Pressing a Shift key
    keyUp    --> for instance, Releasing a pressed Shift key
    sendKeys --> used to send series of characters as text

    Use case : Search text "Actions(class) and Action(interface) in selenium" in this site @ https://jasper-bi-suite.blogspot.com/ by sending the text in Capital letters. 

    1. Locate the "search box" element and store it in WebElement variable. 
    2. Create object "actionsBuilder" for Actions class and pass "driver" in its constructor.
    3.  Build the series of actions on "actionBuilder" object and store it in "Action" interface variable "seriesOfKeyBoardActions" and apply build() method once the series of actions are done.
    4. Perform the series actions using "perform()" method on the above created Action variable say "seriesOfKeyBoardActions" 
    Click on the images to enlarge: 

    The code snippet below holds shifts key and converts the text into capital letters using "keyDown" event and then releases the shift key using "keyUp" event.

    //Search box element locator 
    WebElement searchBox
    = driver.findElement(By.xpath("//input[@name='q']"));

    //Actions object
    Actions actionsBuilder
    = new Actions(driver);

    //Building the series of actions
    Action seriesOfKeyBoardActions
    = actionsBuilder
    .moveToElement(searchBox) //Moves the mouse pointer to the center of the element
    .click() //perform click on the serach box
    .keyDown(searchBox,Keys.SHIFT) // Pressing shift key
    .sendKeys(searchBox,"Actions(class) and Action(interface) in selenium") //sending search text
    .keyUp(searchBox,Keys.SHIFT) // Releasing shift key
    .build(); // building all the above 5 actions

    //Performing the built actions
    seriesOfKeyBoardActions
    .perform();

    Watch this space for walk through video tutorial for below use-case:

    KeyboardEventsSendCaptialLettersForSearchingActionsArcticle.java
    /* Keyboard events demo */
    package keyboard.events.examples;

    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.interactions.Action;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class KeyboardEventsSendCaptialLettersForSearchingActionsArcticle {

    public static void main(String[] args) {

    WebDriver driver;

    //loading Chrome driver from physical drive
    System.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver_83.exe");
    System.setProperty("webdriver.chrome.silentOutput", "true");

    //launch the browser
    driver = new ChromeDriver();

    //navigate to site
    driver.navigate().to("https://jasper-bi-suite.blogspot.com/");

    //maximize the browser
    driver.manage().window().maximize();

    //Search box element locator
    WebElement searchBox = driver.findElement(By.xpath("//input[@name='q']"));

    //Actions object
    Actions actionsBuilder = new Actions(driver);

    //Building the series of actions
    Action seriesOfKeyBoardActions = actionsBuilder
    .moveToElement(searchBox) //Moves the mouse pointer to the center of the element
    .click() //perform click on the serach box
    .keyDown(searchBox,Keys.SHIFT) // Pressing shift key
    .sendKeys(searchBox,"Actions(class) and Action(interface) in selenium") //sending search text
    .keyUp(searchBox,Keys.SHIFT) // Releasing shift key
    .build(); // building all the above 5 actions

    //Performing the built actions
    seriesOfKeyBoardActions.perform();

    //click on Search button
    WebElement searchButton = driver.findElement(By.xpath("//input[@class='gsc-search-button']"));
    searchButton.click();

    //close the browser
    //driver.close();

    //close all the browsers opened by WebDriver during execution and quit the session
    //driver.quit();
    }
    }

    Stay tuned for more automation!

    - Sadakar Pochampalli

    May 23, 2020

    Hi, in this page, we will discuss about Actions(class) and Action(interface) and mouse events example in selenium with some key take away notes.

    For, keyboard events tutorial, click this link.


    Actions

    • It is a class and the package is org.openqa.selenium.interactions.Actions
    • It represents collection of individual Action that you want to perform.
    • Using this class we can handle keyboard and mouse events. i.e., 
      • Keyboard interface methods 
      • Mouse interface methods 

    Action 

    • Action is an interface 
    • It represents single user interaction. 
    • Using this interface, on the Actions object we perform series of actions. 
    • Most widely and must use method is perform() after creating series of actions and storing in Action
    Mouse events examples 
       clickAndHold(),
       clickAndHold(WebElement target),
       moveToElement(WebElement target),
       moveToElement(WebElement target, int xOffset, int yOffset),
       release() ,
       release(WebElement target) and etc. 

      Implements the builder pattern: Builds a CompositeAction containing all actions specified
              by the method calls

    • build() method
      • The build() method is always the final method used
      • All the listed actions will be compiled into a single step.
    • Definition by the book: 
    Generates a composite action containing all actions so far,
    ready to be performed (and resets the internal builder state,
    so subsequent calls to build() will contain fresh sequences).

    Use case : drag and drop images from source location to target 

    1. Locate the source/from element which you want to drag and store it in a WebElement variable.
    2. Locate the target/to element where you want to drop the source element and store it in a WebElement variable. 
    3. We work with Actions(class) & Action(interface) together so let's first create  Actions object "builder" by attaching "driver" object.
    4. Build the series of actions on "builder" object and store it in "Action" interface variable say "drop1Image1".
      NOTE : Must apply build() method at the end.
    5. Perform the series actions using "perform()" method on the above created Action variable say "drop1Image1"
    The code snippet below clicks and holds --> moves --> and releases the images from the source location to target location.
      WebElement drag1FromImage1 = driver.findElement(By.xpath("//*[@id='gallery']//img[contains(@alt,'The peaks of High Tatras')]"));
      WebElement dropImagesTo
      = driver.findElement(By.xpath("//div[@id='trash']"));

      Actions builder
      = new Actions(driver);
      Action drop1Image1
      = builder.clickAndHold(drag1FromImage1)
      .moveToElement(dropImagesTo)
      .release(dropImagesTo)
      .build();
      drop1Image1
      .perform();


      Demo site credits and courtesyhttps://www.globalsqa.com/demo-site/draganddrop/
      Click on the images to enlarge: 
      Before mouse events: 

      After mouse events: 


      Watch this space for walk through video tutorial for the example

      MouseEventsActionsDragAndDropImagesDemo.java
      //drag and drop - mouse events demo
      package mouse.event.drag.and.drop.elements;

      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.interactions.Actions;
      import org.openqa.selenium.interactions.Action;

      public class MouseEventsActionsDragAndDropImagesDemo {

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

      WebDriver driver
      ;

      System
      .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver_83.exe");
      System
      .setProperty("webdriver.chrome.silentOutput", "true");

      driver
      = new ChromeDriver();
      driver
      .get("https://www.globalsqa.com/demo-site/draganddrop/");

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

      //drag and drop image from one location to another on web-page

      // switch to Frame
      driver
      .switchTo().frame(driver.findElement(By.xpath("//iframe[@class='demo-frame lazyloaded']")));

      // source/from location
      WebElement drag1FromImage1
      = driver.findElement(By.xpath("//*[@id='gallery']//img[contains(@alt,'The peaks of High Tatras')]"));
      WebElement drag2FromImage2
      = driver.findElement(By.xpath("//*[@id='gallery']//img[contains(@alt,'The chalet at the Green mountain lake')]"));
      WebElement drag3FromImage3
      = driver.findElement(By.xpath("//*[@id='gallery']//img[contains(@alt,'Planning the ascent')]"));
      WebElement drag4FromImage4
      = driver.findElement(By.xpath("//*[@id='gallery']//img[contains(@alt,'On top of Kozi kopka')]"));

      // target/to location
      WebElement dropImagesTo
      = driver.findElement(By.xpath("//div[@id='trash']"));

      //Object of Actions class
      Actions builder
      = new Actions(driver);

      //Building the series of actions
      Action drop1Image1
      = builder.clickAndHold(drag1FromImage1) // without releasing clicks the the image source location
      .moveToElement(dropImagesTo) //moves the mouse to the middle of target location
      .release(dropImagesTo) //releases the mouse at the current mouse i.e, at target location
      .build(); // build all the above 3 actions

      //Performing the built actions
      drop1Image1
      .perform();

      Action drop2Image2
      = builder.clickAndHold(drag2FromImage2)
      .moveToElement(dropImagesTo)
      .release(dropImagesTo)
      .build();
      drop2Image2
      .perform();

      Action drop3Image3
      = builder.clickAndHold(drag3FromImage3)
      .moveToElement(dropImagesTo)
      .release(dropImagesTo)
      .build();
      drop3Image3
      .perform();

      Action drop4Image4
      = builder.clickAndHold(drag4FromImage4)
      .moveToElement(dropImagesTo)
      .release(dropImagesTo)
      .build();
      drop4Image4
      .perform();

      Thread
      .sleep(5000);
      driver
      .quit();

      }
      }

      Stay tuned for more automation!

      - Sadakar Pochampalli

      May 23, 2020

      May 22, 2020

      Hi, In this post, we will see the differences between WebElement interface most commonly used methods - isDisplayed(), isEnabled() and isSelected() with real time example scenarios.

      IsEnabled() has some special purpose of verifying elements such as buttons enabled or disabled status. Let's look into each of them.

      Image and test site courtesy : https://www.testandquiz.com/selenium/testing.html

      isDisplayed() 
      • To verify presence of a web-element with in the web page. 
      • This method returns either true or false boolean values. 
      • If the element is present it returns "true" otherwise it returns "false". 
      • This method avoids the problem of having to parse an element's "style" attribute.
      • This method can be applicable for almost all of the elements on web-page.
      Example:  
      HTML for : Sample
      <b xpath="1">This is sample text.</b>

      Selenium snippet
      //isDisplayed() | Text on web page | Example : This is sample text.
      WebElement ThisIsSimpleText
      = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
      boolean b1 = ThisIsSimpleText.isDisplayed();
      System
      .out.println("Verify dispaly status of the text \"This is sample Text\"="+b1);

      isEnabled()

      • To verify if an element is enabled or disabled on web-page. 
      • Returns "ture" if element is enabled and returns "false" if an element is disabled. 
      • Examples: Mostly used with button elements, locked/disabled text input elements. 
      Example :
      Please find this blog post for a real time login use case example in which you will see "Sign Up" button is enabled after selecting a check box of terms and conditions.
        isSelected() 
        • Returns whether an element say check box or radio button is selected or not. 
        • If selected returns "true", if not selected returns "false". 
        • Examples: Check boxes, drop downs , radio buttons
        Example:
        HTML
        <input id="male" type="radio" name="gender" value="male" xpath="1">
          Selenium snippet
          //isSelected()  | Example :  male radio button
          WebElement maleRaditoButton
          = driver.findElement(By.xpath("//input[@id='male']"));
          boolean b2 = maleRaditoButton.isSelected(); //false
          System
          .out.println("Verify male radio button selected or not before click = "+b2);
          //select the male radio button and verify isSelected()
          maleRaditoButton
          .click();
          boolean b3 = maleRaditoButton.isSelected(); //true
          System
          .out.println("Verify male radio button selected or not after click = "+b3);

          Checkout this video tutorial to understand the example below

          WebElementInterfaceMethods_isDisplayedisSelectedDemo.java
          package selenium.webelement.methods;

          /* isDisplayed() , and isSelected() */

          import java.util.concurrent.TimeUnit;

          import org.openqa.selenium.By;
          import org.openqa.selenium.PageLoadStrategy;
          import org.openqa.selenium.WebDriver;
          import org.openqa.selenium.WebElement;
          import org.openqa.selenium.chrome.ChromeDriver;
          import org.openqa.selenium.chrome.ChromeDriverService;
          import org.openqa.selenium.chrome.ChromeOptions;

          public class WebElementInterfaceMethods_isDisplayedisSelectedDemo {

          public static void main(String[] args) {

          WebDriver driver
          ;

          //loading Chrome driver from physical drive
          System
          .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");

          System
          .setProperty("webdriver.chrome.silentOutput", "true");
          //System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

          //launch the browser
          driver
          = new ChromeDriver();

          //navigate to site
          driver
          .navigate().to("https://www.testandquiz.com/selenium/testing.html");

          //maximize the browser
          driver
          .manage().window().maximize();

          //isDisplayed() | Text on web page | Example : This is sample text.
          WebElement ThisIsSimpleText
          = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
          boolean b1 = ThisIsSimpleText.isDisplayed();
          System
          .out.println("Verify dispaly status of the text \"This is sample Text\"="+b1);

          //isSelected() | Example : male radio button
          WebElement maleRaditoButton
          = driver.findElement(By.xpath("//input[@id='male']"));
          boolean b2 = maleRaditoButton.isSelected();
          System
          .out.println("Verify male radio button selected or not before click = "+b2);

          //select the male radio button and verify isSelected()
          maleRaditoButton
          .click();
          boolean b3 = maleRaditoButton.isSelected();
          System
          .out.println("Verify male radio button selected or not after click = "+b3);


          //close the browser
          driver
          .close();

          //close all the browsers opened by WebDriver during execution and quit the session
          driver
          .quit();
          }
          }


          May 22, 2020

          May 20, 2020


          XPath
          • XPath = XML Path
          • It is a type of query language to identify any element on the web page. 
          • Syntax
            //tagname[@attribute='value']
          • Writing XPath for complex applications sometimes cumbersome task.
          • There are plenty of plug-ins available for chrome to find Xpaths and one such tool is  "Chropath" pulg-in. 
          • Take a look at the below image to find relative XPath for "Email or Phone" text input.
            Tap on the image to get better visibility of  content
            Let's understand with an example, Identify gmail's  "Email or phone" text input with xpath
            Tap on the image to get better visibility:

            HTML
            <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username" spellcheck="false" tabindex="0" aria-label="Email or phone" name="identifier" value="" autocapitalize="none" id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="">

            from the above HTML,  tagname is input  | type is an attribute  | value is email

            Xpath to locate the "Email or phone" is
            //input[@type='email']

            Java-selenium identifies the element with the following xpath locator
            driver.findElement(By.xpath("//input[@id='identifierId']"))

            Watch this ~4 min video tutorial example for automating gmail login process in which use xpath locators for "Email or Phone" or "Password"  or "Next" buttons. 


            java-selenium code to identify gmail login using xpath locators
            xpathLocatorGmailLoginDemo.java
            //x-path locator example

            package selenium.locators.examples;
            import java.util.concurrent.TimeUnit;
            import org.openqa.selenium.By;
            import org.openqa.selenium.Keys;
            import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.chrome.ChromeDriver;

            public class xpathLocatorGmailLoginDemo {

            public static void main(String[] args) {

            WebDriver driver
            ;

            System
            .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
            System
            .setProperty("webdriver.chrome.silentOutput", "true");

            driver
            = new ChromeDriver();
            driver
            .manage().window().maximize();

            driver
            .navigate().to("https://mail.google.com/");

            //locate "Email or Phone" text box input using "xpath" and enter email
            driver
            .findElement(By.xpath("//input[@id='identifierId']")).sendKeys("java.selenium2021@gmail.com");

            // locate "Next" button and click
            driver
            .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

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

            //locate "Enter your password" text box input using "xpath" and enter password
            WebElement elePassword
            =driver.findElement(By.xpath("//input[@name='password']"));
            elePassword
            .sendKeys("JavaSelenium2021");

            elePassword
            .sendKeys(Keys.TAB);
            elePassword
            .sendKeys(Keys.TAB);

            // locate "Next" button and click
            driver
            .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

            //driver.close();
            }
            }

            May 20, 2020

            Hi , In this post - I'm writing my learning experiences on various methods of "WebElement" interface.
            Test site courtesy : 

            Watch the below ~1 min video for end-to-end execution 
            getText()
            • getText() method gets you the visible text or inner text of an element. 
            • That is it fetches text between the opening and closing tags. 
            • For instance, the following text between bold tags can be fetched using getText() method.
              <b xpath="1">This is sample text.</b>
            • Store the locator in a Weblement variable and then use getText()
              //getText() example --> locate text "This is sample text." on page and display the text
              WebElement ThisIsSimpleText
              = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
              String displayThisIsSimpleText
              = ThisIsSimpleText.getText();
              System
              .out.println(displayThisIsSimpleText);
            sendKeys()
            • This method allows users to enter data into editable elements such as text boxes or search boxes.
            • For instance, first name is a text box input and using sendKeys() method enter input value
              <input id="fname" type="text" name="firstName" xpath="1">
            • Code snippet
              //sendKeys("sadakar") example --> locate TextBox input and enter first name
              WebElement firstName
              = driver.findElement(By.xpath("//input[@id='fname']"));
              firstName
              .sendKeys("Sadakar");
            clear()
            • clear() method clears any text already entered or displayed in text box or search box inputs. 
            • Some applications may use default values in editable forms so clear them before entering new.
            • For instance, clear the already existing text in "first name" text box and enter new value
              //clear() --> clear TextBox input and re-enter first name
              firstName
              .clear();
              firstName
              .sendKeys("Hasini");
            getAttribute("<attribute>")
            • getAttribute() method returns the current value of a given attribute as a string.
              <input id="fname" type="text" name="firstName" xpath="1">
            • id, type, name , xpath and vlaue(not given above statement) are attributes of first name element HTML 
            • For instance, the following snippet for firstname text field fetches the value displayed on the form then the values of the corresponding attributes
              //getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
              firstName
              .getAttribute("value");
              System
              .out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
              System
              .out.println("Value of value attribute="+firstName.getAttribute("value"));
              System
              .out.println("Value of id attribute="+firstName.getAttribute("id"));
              System
              .out.println("Value of type attribute="+firstName.getAttribute("type"));
              System
              .out.println("Value of name attribute="+firstName.getAttribute("name"));
            Handling radio buttons and check boxes using - click() method
            • Toggling(select or deselect) on/off are the actions performed for radio buttons or check boxes. 
            • Using click() method toggling can be done. 
            • For instance, take a look at the following code snippet - "male" radio button and check boxes for testings labels are selected.
              //radio button click example --> locate "male" radio button and select it
              WebElement male
              = driver.findElement(By.xpath("//input[@id='male']"));
              male
              .click();

              //check box click example - locate "Automation Testing" check box and tick it
              WebElement automationTesting
              = driver.findElement(By.xpath("//input[@class='Automation']"));
              automationTesting
              .click();

              //check box click example - locate "Performance Testing" check box and tick it
              WebElement performanceTesting
              = driver.findElement(By.xpath("//input[@class='Performance']"));
              performanceTesting
              .click();

            Complete java class for above examples: WebElementInterfaceMethodsDemo.java
            package selenium.webelement.methods;

            import java.util.concurrent.TimeUnit;

            import org.openqa.selenium.By;
            import org.openqa.selenium.PageLoadStrategy;
            import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.chrome.ChromeDriver;
            import org.openqa.selenium.chrome.ChromeDriverService;
            import org.openqa.selenium.chrome.ChromeOptions;

            public class WebElementInterfaceMethodsDemo {

            public static void main(String[] args) {

            WebDriver driver
            ;

            //loading Chrome driver from physical drive
            System
            .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");

            System
            .setProperty("webdriver.chrome.silentOutput", "true");
            //System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

            //launch the browser
            driver
            = new ChromeDriver();

            //navigate to site
            driver
            .navigate().to("https://www.testandquiz.com/selenium/testing.html");

            //maximize the browser
            driver
            .manage().window().maximize();

            //getText() example --> locate text "This is sample text." on page and display the text
            WebElement ThisIsSimpleText
            = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
            String displayThisIsSimpleText
            = ThisIsSimpleText.getText();
            System
            .out.println(displayThisIsSimpleText);

            //sendKeys("sadakar") example --> locate TextBox input and enter first name
            WebElement firstName
            = driver.findElement(By.xpath("//input[@id='fname']"));
            firstName
            .sendKeys("Sadakar");

            //clear() --> clear TextBox input and re-enter first name
            firstName
            .clear();
            firstName
            .sendKeys("Hasini");

            //getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
            firstName
            .getAttribute("value");
            System
            .out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
            System
            .out.println("Value of value attribute="+firstName.getAttribute("value"));
            System
            .out.println("Value of id attribute="+firstName.getAttribute("id"));
            System
            .out.println("Value of type attribute="+firstName.getAttribute("type"));
            System
            .out.println("Value of name attribute="+firstName.getAttribute("name"));

            //radio button click example --> locate "male" radio button and select it
            WebElement male
            = driver.findElement(By.xpath("//input[@id='male']"));
            male
            .click();

            //check box click example - locate "Automation Testing" check box and tick it
            WebElement automationTesting
            = driver.findElement(By.xpath("//input[@class='Automation']"));
            automationTesting
            .click();

            WebElement performanceTesting
            = driver.findElement(By.xpath("//input[@class='Performance']"));
            performanceTesting
            .click();

            //close the browser
            driver
            .close();

            //close all the browsers opened by WebDriver during execution and quit the session
            driver
            .quit();
            }
            }

            May 20, 2020

            Hi,

            In this post, you will see demonstration of "tagName" locator usage. 

            "tagName"  is one of the 8 locators supported by selenium.

            For instance, display all the anchors "a" or "images" alternative texts on amazaon india page   @ https://www.amazon.in/

            selenium identifies the "a" and "image" tags with the following java statements.

            List<WebElement> links = driver.findElements(By.tagName("a"));
            List<WebElement> images = driver.findElements(By.tagName("img"));

            tagNameLocatorDemo.java
            package selenium.locators.examples;
            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 tagNameLocatorDemo {

            public static void main(String[] args) {

            WebDriver driver
            ;

            System
            .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
            System
            .setProperty("webdriver.chrome.silentOutput", "true");

            driver
            = new ChromeDriver();

            driver
            .navigate().to("https://www.amazon.in/");
            driver
            .manage().window().maximize();

            // storing anchor - a tags in links List<WebElement> variable
            List
            <WebElement> links = driver.findElements(By.tagName("a"));

            // printing the size of list
            System
            .out.println("Size of list="+links.size());

            // print the top 5 Text of anchors
            System
            .out.println("-- Printing top 5 anchors text--");
            for(int i=0;i<links.size();i++) {
            System
            .out.println(links.get(i).getText());
            if(i==4)
            break;
            }
            System
            .out.println("------------------------------------");

            // storing images - img tags in images List<WebElement> variable
            List
            <WebElement> images = driver.findElements(By.tagName("img"));

            // foreach loop with WebElements
            // if wants to break the loop on a particular index go with regular loop
            System
            .out.println("-- Printing images alternative texts --");
            for(WebElement w2 : images) {
            System
            .out.println(w2.getAttribute("alt"));
            }

            }
            }

            Watch this ~ 1.5 min video for end-to-end example execution



            May 20, 2020

            May 19, 2020

            Hi,

            In this post, you will see demonstration of "className" locator usage. 

            "classname" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action(s).

            For instance, Login to gmail  @ https://mail.google.com/
            Let's see how to identify the name locators of login elements for gmail web application.

            Email or Phone input text input HTML with "name" locator 
            <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username" spellcheck="false" tabindex="0" aria-label="Email or phone" name="identifier" value="" autocapitalize="none" id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="" badinput="false" aria-invalid="false" xpath="1">

            selenium identifies the above input element(Email or Phone) using "className" locator with the following java statement. 
            driver.findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

            Tap on the image to get better visibility: 
            To avoid StaleElementReferenceException for other elements locators having the same class name ,  I am taking xpaths to find them, for instance , password has the same className i.e., class="whsOnd zHQkBf"  so instead of having className for password taking xpath //input[@name='password']


            classNameLocatorDemo.java
            package selenium.locators.examples;

            import java.util.concurrent.TimeUnit;
            import org.openqa.selenium.By;
            import org.openqa.selenium.Keys;
            import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.chrome.ChromeDriver;

            public class classNameLocatorDemo {

            public static void main(String[] args) {

            WebDriver driver
            ;

            System
            .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
            System
            .setProperty("webdriver.chrome.silentOutput","true" );

            driver
            = new ChromeDriver();

            driver
            .navigate().to("https://mail.google.com/");
            driver
            .manage().window().maximize();

            //finding "Email or Phone" input text by clasName locator and enter value
            driver
            .findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

            // click on "Next" button - This is an xpath example that will be covered in later sessions
            driver
            .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

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

            // locate "Enter your password" text input with xpath locator and enter password say --> JavaSelenium2021
            // If we take className for this input we will end up with
            // Exception in thread "main" org.openqa.selenium.StaleElementReferenceException:
            // stale element reference: element is not attached to the page document

            WebElement elePassword
            =driver.findElement(By.xpath("//input[@name='password']"));
            elePassword
            .sendKeys("JavaSelenium2021");

            elePassword
            .sendKeys(Keys.TAB);
            elePassword
            .sendKeys(Keys.TAB);

            // click on "Next" button - This is again an xpath example.
            driver
            .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

            //close the driver
            //driver.close();
            }
            }


            May 19, 2020

            Pages

            Feedback
            randomness