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

    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