Selenium Automation

 

Selenium Automation



Selenium is a free (open-source) automated testing framework used to validate web applications across different browsers and platforms. You can use multiple programming languages like Java, C#, Python, etc. to create Selenium Test Scripts. Testing done using the Selenium testing tool is usually referred to as Selenium Testing. 

Selenium Tool Suite

Selenium Software is not just a single tool but a suite of software, each piece catering to different Selenium QA testing needs of an organization. Here is the list of tools

  • Selenium Integrated Development Environment (IDE)
  • Selenium Remote Control (RC)
  • WebDriver
  • Selenium Grid



Who developed Selenium?

Since Selenium is a collection of different tools, it also had different developers. Below are the key persons who made notable contributions to the Selenium Project Primarily, Selenium was created by Jason Huggins in 2004. An engineer at ThoughtWorks, he was working on a web application that required frequent testing. Having realized that their application’s repetitious Manual Testing was becoming increasingly inefficient, he created a JavaScript program that would automatically control the browser’s actions. He named this program the “JavaScriptTestRunner.”

What is WebDriver?

The WebDriver proves to be better than Selenium IDE and Selenium RC in many aspects. It implements a more modern and stable approach in automating the browser’s actions. WebDriver, unlike Selenium RC, does not rely on JavaScript for Selenium Automation Testing. It controls the browser by directly communicating with it.

Selenium installation is a 3 step process:

1.      Install Java SDK

2.      Install Eclipse

3.      Install Selenium Webdriver Files

 

WebDriver Code

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

//comment the above line and uncomment below line to use Chrome

//import org.openqa.selenium.chrome.ChromeDriver;

public class PG1 {

 

 

    public static void main(String[] args) {

        // declaration and instantiation of objects/variables

        System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

               WebDriver driver = new FirefoxDriver();

               //comment the above 2 lines and uncomment below 2 lines to use Chrome

                //System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");

               //WebDriver driver = new ChromeDriver();

       

        String baseUrl = "http://demo.guru99.com/test/newtours/";

        String expectedTitle = "Welcome: Mercury Tours";

        String actualTitle = "";

 

        // launch Fire fox and direct it to the Base URL

        driver.get(baseUrl);

 

        // get the actual value of the title

        actualTitle = driver.getTitle();

 

        /*

         * compare the actual title of the page with the expected one and print

         * the result as "Passed" or "Failed"

         */

        if (actualTitle.contentEquals(expectedTitle)){

            System.out.println("Test Passed!");

        } else {

            System.out.println("Test Failed");

        }

      

        //close Fire fox

        driver.close();

      

    }

 

}

 

 

Here is a Selenium sample code that locates an element by its id. Facebook is used as the Base URL.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class PG2 {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();

        String baseUrl = "http://www.facebook.com";

        String tagName = "";

       

        driver.get(baseUrl);

        tagName = driver.findElement(By.id("email")).getTagName();

        System.out.println(tagName);

        driver.close();

        System.exit(0);

}

}

 

 



Common Commands

Instantiating Web Elements

Instead of using the long “driver.findElement(By.locator())” syntax every time you will access a particular element, we can instantiate a WebElement object for it. The WebElement class is contained in the “org.openqa.selenium.*” package.



Clicking on an Element

Clicking is perhaps the most common way of interacting with web elements. The click() method is used to simulate the clicking of any element.  The following Selenium Java example shows how click() was used to click on Mercury Tours’  “Sign-In” button.




Following things must be noted when using the click() method.

  • It does not take any parameter/argument.
  • The method automatically waits for a new page to load if applicable.
  • The element to be clicked-on, must be visible (height and width must not be equal to zero).

Get Commands

Get commands fetch various important information about the page/element. Here are some important “get” commands you must be familiar with.

Commands

Usage

get()

Sample usage:

  • It automatically opens a new browser window and fetches the page that you specify inside its parentheses.
  • It is the counterpart of Selenium IDE’s “open” command.
  • The parameter must be a String object.

getTitle()

Sample usage:

  • Needs no parameters
  • Fetches the title of the current page
  • Leading and trailing white spaces are trimmed
  • Returns a null string if the page has no title

getPageSource()

Sample usage:

  • Needs no parameters
  • Returns the source code of the page as a String value

getCurrentUrl()

Sample usage:

  • Needs no parameters
  • Fetches the string representing the current URL that the browser is looking at

getText()

Sample usage:

  • Fetches the inner text of the element that you specify

Navigate commands

These commands allow you to  refresh,go-into and switch back and forth between different web pages.

navigate().to()

Sample usage:

  • It automatically opens a new browser window and fetches the page that you specify inside its parentheses.
  • It does exactly the same thing as the get() method.

navigate().refresh()

Sample usage:

  • Needs no parameters.
  • It refreshes the current page.

navigate().back()

Sample usage:

  • Needs no parameters
  • Takes you back by one page on the browser’s history.

navigate().forward()

Sample usage:

  • Needs no parameters
  • Takes you forward by one page on the browser’s history.

Closing and Quitting Browser Windows

close()

Sample usage:

  • Needs no parameters
  • It closes only the browser window that WebDriver is currently controlling.

quit()

Sample usage:

  • Needs no parameters
  • It closes all windows that WebDriver has opened.

package newproject;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class PG3 {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.popuptest.com/popuptest2.html");

        driver.quit();  // using QUIT all windows will close

    }

}

 

 

 

Waits

There are two kinds of waits.

1.      Implicit wait – used to set the default waiting time throughout the program

2.      Explicit wait – used to set the waiting time for a particular instance only

Implicit Wait

  • It is simpler to code than Explicit Waits.
  • It is usually declared in the instantiation part of the code.
  • You will only need one additional package to import.

To start using an implicit wait, you would have to import this package into your code.

import java.util.concurrent.TimeUnit;

Then on the instantiation part of your code, add this.



Explicit Wait

Explicit waits are done using the WebDriverWait and ExpectedCondition classes. For the following Selenium WebDriver example, we shall wait up to 10 seconds for an element whose id is “username” to become visible before proceeding to the next command. Here are the steps.

Step 1

Import these two packages:



Step 2

Declare a WebDriverWait variable. In this example, we will use “myWaitVar” as the name of the variable.



Step 3

Use myWaitVar with ExpectedConditions on portions where you need the explicit wait to occur. In this case, we will use explicit wait on the “username” (Mercury Tours HomePage) input before we type the text “tutorial” onto it.



Conditions

Following  methods are used  in conditional and looping operations —

  • isEnabled() is used when you want to verify whether a certain element is enabled or not before executing a command.



  • isDisplayed() is used when you want to verify whether a certain element is displayed or not before executing a command.



  • isSelected() is used when you want to verify whether a certain check box, radio button, or option in a drop-down box is selected. It does not work on other elements.



Using ExpectedConditions

The ExpectedConditions class offers a wider set of conditions that you can use in conjunction with WebDriverWait’s until() method.

Below are some of the most common ExpectedConditions methods.

  • alertIsPresent() – waits until an alert box is displayed.



  • elementToBeClickable() – Waits until an element is visible and, at the same time, enabled. The sample Selenium Code below will wait until the element with id=”username” to become visible and enabled first before assigning that element as a WebElement variable named “txtUserName”.



  • frameToBeAvailableAndSwitchToIt() – Waits until the given frame is already available, and then automatically switches to it.



Catching Exceptions

When using isEnabled(), isDisplayed(), and isSelected(), WebDriver assumes that the element already exists on the page. Otherwise, it will throw a NoSuchElementException. To avoid this, we should use a try-catch block so that the program will not be interrupted.

WebElement txtbox_username = driver.findElement(By.id("username"));

try{

        if(txtbox_username.isEnabled()){

            txtbox_username.sendKeys("tutorial");

        }

    }

 

catch(NoSuchElementException nsee){

            System.out.println(nsee.toString());

 }

If you use explicit waits, the type of exception that you should catch is the “TimeoutException”.



 

Locators in Selenium

 

What are Locators?

Locator is a command that tells Selenium IDE which GUI elements ( say Text Box, Buttons, Check Boxes etc) its needs to operate on.  Identification of correct GUI elements is a prerequisite to creating an automation script. But accurate identification of GUI elements is more difficult than it sounds. Sometimes, you end up working with incorrect GUI elements or no elements at all!  Hence, Selenium provides a number of Locators to precisely locate a GUI element

Locating by ID

This is the most common way of locating elements since ID’s are supposed to be unique for each element.

Step 1. Since this tutorial was created, Facebook has changed their Login Page Design. Use this demo page http://demo.guru99.com/test/facebook.html for testing. Inspect the “Email or Phone” text box using Firebug and take note of its ID. In this case, the ID is “email.”



Step 2. Launch Selenium IDE and enter “id=email” in the Target box. Click the Find button and notice that the “Email or Phone” text box becomes highlighted with yellow and bordered with green, meaning, Selenium IDE was able to locate that element correctly.



Locating by Name

Locating elements by name are very similar to locating by ID, except that we use the “name=” prefix instead.

Target Format: name=name of the element

In the following demonstration, we will now use Mercury Tours because all significant elements have names.

Step 1. Navigate to http://demo.guru99.com/test/newtours/ and use Firebug to inspect the “User Name” text box. Take note of its name attribute.



Here, we see that the element’s name is “userName”.

Step 2. In Selenium IDE, enter “name=userName” in the Target box and click the Find button. Selenium IDE should be able to locate the User Name text box by highlighting it.



How To Locate Element By Name using Filters

Filters can be used when multiple elements have the same name. Filters are additional attributes used to distinguish elements with the same name.

Target Format: name=name_of_the_element filter=value_of_filter

Let’s see an example –

Step 1) Log on to Mercury Tours.

Log on to Mercury Tours using “tutorial” as the username and password. It should take you to the Flight Finder page shown below.


Step 2) Using firebug use VALUE attributes.

Using Firebug, notice that the Round Trip and One Way radio buttons have the same name “tripType.” However, they have different VALUE attributes so we can use each of them as our filter.



Step 3) Click on the first line.

  • We are going to access the One Way radio button first. Click the first line on the Editor.
  • In the Command box of Selenium IDE, enter the command “click”.
  • In the Target box, enter “name=tripType value=oneway”. The “value=oneway” portion is our filter.



Step 4) Click the Find button.

Notice that Selenium IDE is able to highlight the One Way radio button with green – meaning that we are able to access the element successfully using its VALUE attribute.



Step 5) Select One Way radio button.

Press the “X” key in your keyboard to execute this click command. Notice that the One Way radio button became selected.



You can do the exact same thing with the Round Trip radio button, this time, using “name=tripType value=roundtrip” as your target.

Locating by Link Text

This type of CSS locator in Selenium applies only to hyperlink texts. We access the link by prefixing our target with “link=” and then followed by the hyperlink text.

Target Format: link=link_text

In this example, we shall access the “REGISTER” link found on the Mercury Tours homepage.

Step 1.

  • First, make sure that you are logged off from Mercury Tours.
  • Go to Mercury Tours homepage.

Step 2.

  • Using Firebug, inspect the “REGISTER” link. The link text is found between and tags.
  • In this case, our link text is “REGISTER”. Copy the link text.


Locating by DOM – getElementById

Let us focus on the first method – using the getElementById method of DOM in Selenium. The syntax would be:

Syntax

document.getElementById("id of the element")

  • id of the element = this is the value of the ID attribute of the element to be accessed. This value should always be enclosed in a pair of parentheses (“”).
  • Step 1. Use this demo page http://demo.guru99.com/test/facebook.html Navigate to it and use Firebug to inspect the “Keep me logged in” check box. Take note of its ID.

    How to use Locators in Selenium IDE

    We can see that the ID we should use is “persist_box”.

Step 2. Open Selenium IDE and in the Target box, enter “document.getElementById(“persist_box”)” and click Find. Selenium IDE should be able to locate the “Keep me logged in” check box. Though it cannot highlight the interior of the check box, Selenium IDE can still surround the element with a bright green border as shown below.

How to use Locators in Selenium IDE

Locating by DOM – getElementsByName

The getElementById method can access only one element at a time, and that is the element with the ID that you specified. The getElementsByName method is different. It collects an array of elements that have the name that you specified. You access the individual elements using an index which starts at 0.



getElementById

  • It will get only one element for you.
  • That element bears the ID that you specified inside the parentheses of getElementById().


getElementsByName

  • It will get a collection of elements whose names are all the same.
  • Each element is indexed with a number starting from 0 just like an array
  • You specify which element you wish to access by putting its index number into the square brackets in getElementsByName’s syntax below.


Syntax

document.getElementsByName(“name“)[index]

  • name = name of the element as defined by its ‘name’ attribute
  • index = an integer that indicates which element within getElementsByName’s array will be used.

Step 1. Navigate to Mercury Tours’ Homepage and login using “tutorial” as the username and password. Firefox should take you to the Flight Finder screen.

Step 2. Using Firebug, inspect the three radio buttons at the bottom portion of the page (Economy class, Business class, and First class radio buttons). Notice that they all have the same name which is “servClass”.

How to use Locators in Selenium IDE

Step 3. Let us access the “Economy class” radio button first. Of all these three radio buttons, this element comes first, so it has an index of 0. In Selenium IDE, type “document.getElementsByName(“servClass”)[0]” and click the Find button. Selenium IDE should be able to identify the Economy class radio button correctly.

How to use Locators in Selenium IDE

Step 4. Change the index number to 1 so that your Target will now become document.getElementsByName(“servClass”)[1]. Click the Find button, and Selenium IDE should be able to highlight the “Business class” radio button, as shown below.

How to use Locators in Selenium IDE

Locating by XPath

XPath is the language used when locating XML (Extensible Markup Language) nodes. Since HTML can be thought of as an implementation of XML, we can also use XPath in locating HTML elements.

        Advantage: It can access almost any element, even those without class, name, or id attributes.

        Disadvantage: It is the most complicated method of identifying elements because of too many different rules and considerations.

Fortunately, Firebug can automatically generate XPath Selenium locators. In the following example, we will access an image that cannot possibly be accessed through the methods we discussed earlier.

Step 1. Navigate to Mercury Tours Homepage and use Firebug to inspect the orange rectangle to the right of the yellow “Links” box. Refer to the image below.



Step 2. Right click on the element’s HTML code and then select the “Copy XPath” option.



Step 3. In Selenium IDE, type one forward slash “/” in the Target box then paste the XPath that we copied in the previous step. The entry in your Target box should now begin with two forward slashes “//”.



Step 4. Click on the Find button. Selenium IDE should be able to highlight the orange box as shown below.




 

 


package com.sample.stepdefinitions;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class NameDemo {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

 

System.setProperty("webdriver.chrome.driver", "D:\\3rdparty\\chrome\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

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

 

driver.get("http://demo.guru99.com/test/ajax.html");

 

// Find the radio button for “No” using its ID and click on it

driver.findElement(By.id("no")).click();

       

//Click on Check Button

driver.findElement(By.id("buttoncheck")).click();

 

}

 

}

 

 

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 NameDemo {

 

public static void main(String[] args) {

 

    System.setProperty("webdriver.chrome.driver", "X://chromedriver.exe");

    WebDriver driver = new ChromeDriver();

    driver.get("http://demo.guru99.com/test/ajax.html");

    List<WebElement> elements = driver.findElements(By.name("name"));

    System.out.println("Number of elements:" +elements.size());

 

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

      System.out.println("Radio button text:" + elements.get(i).getAttribute("value"));

    }

  }

}

 

Selenium Form WebElement: TextBox, Button, sendkeys(), click()

orms are the fundamental web elements to receive information from the website visitors. Web forms have different GUI elements like Text boxes, Password fields, Checkboxes, Radio buttons, dropdowns, file inputs, etc.

We will see how to access these different form elements using Selenium Web Driver with Java. Selenium encapsulates every form element as an object of WebElement. It provides API to find the elements and take action on them like entering text into text boxes, clicking the buttons, etc. We will see the methods that are available to access each form element.

In this tutorial, we will see how to identify the following form elements

Introduction to WebElement, findElement(), findElements()

Selenium Web Driver encapsulates a simple form element as an object of WebElement.

There are various techniques by which the WebDriver identifies the form elements based on the different properties of the Web elements like ID, Name, Class, XPath, Tagname, CSS Selectors, link Text, etc.

Web Driver provides the following two WebElement methods to find the elements.

  • findElement() – finds a single web element and returns as a WebElement Selenium object.
  • findElements() – returns a list of WebElement objects matching the locator criteria.

Let’s see the code snippets to get a single element – Text Field in a web page as an object of WebElement using findElement() method. We shall cover the findElements() method of finding multiple elements in subsequent tutorials.

Step 1:
We need to import this package to create objects of Web Elements



Step 2:
We need to call the findElement() method available on the WebDriver class and get an object of WebElement.

Refer below to see how it is done.

Input Box

Input boxes refer to either of these two types:

1.      Text Fields– Selenium input text boxes that accept typed values and show them as they are.

2.      Password Fields– text boxes that accept typed values but mask them as a series of special characters (commonly dots and asterisks) to avoid sensitive values to be displayed.



Locators

The method findElement() takes one parameter which is a locator to the element. Different locators like By.id(), By.name(), By.xpath(), By.CSSSelector() etc. locate the elements in the page using their properties like“““ id, name or path, etc.

You can use plugins like Fire path to get help with getting the id, xpath, etc. of the elements.

Using the example site http://demo.guru99.com/test/login.html given below is the code to locate the “Email address” text field using the id locator and the “Password “field using the name locator.



1.      Email text field is located by Id

2.      Password field is located by name

sendkeys in Selenium

sendkeys() in Selenium is a method used to enter editable content in the text and password fields during test execution. These fields are identified using locators like name, class, id, etc. It is a method available on the web element. Unlike the type method, sendkeys() method does not replace existing text in any text box.

Entering Values in Input Boxes

To enter text into the Text Fields and Password Fields, sendKeys() is the method available on the WebElement in Selenium.

Using the same example of http://demo.guru99.com/test/login.html site, here is how we find the Text field and Password fields and enter text in Selenium.


1.      Find the “Email Address” Text field using the id locator.

2.      Find the “Password” field using the name locator

3.      Enter text into the “Email Address” using the Selenium sendkeys method.

4.      Enter a password into the “Password” field using the sendKeys() method.

Deleting Values in Input Boxes

The clear() method is used to delete the text in an input box. This method does not need a parameter. The code snippet below will clear out the text from the Email or Password fields



Buttons

The Selenium click button can be accessed using the click() method.

In the example above

1.      Find the button to Sign in

2.      Click on the “Sign-in” Button in the login page of the site to login to the site.



Submit Buttons

Submit buttons are used to submit the entire form to the server. We can either use the click () method on the web element like a normal button as we have done above or use the submit () method on any web element in the form or on the submit button itself.



When submit() is used, WebDriver will look up the DOM to know which form the element belongs to, and then trigger its submit function.

import org.openqa.selenium.By;       

import org.openqa.selenium.WebDriver;        

import org.openqa.selenium.chrome.ChromeDriver;             

import org.openqa.selenium.*;        

 

public class Form {                          

    public static void main(String[] args) {                                                              

              

        // declaration and instantiation of objects/variables       

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

        WebDriver driver = new ChromeDriver();                                     

                      

        String baseUrl = "http://demo.guru99.com/test/login.html";                                

        driver.get(baseUrl);                                

 

        // Get the WebElement corresponding to the Email Address(TextField)        

        WebElement email = driver.findElement(By.id("email"));                                                   

 

        // Get the WebElement corresponding to the Password Field          

        WebElement password = driver.findElement(By.name("passwd"));                                             

 

        email.sendKeys("abcd@gmail.com");                                  

        password.sendKeys("abcdefghlkjl");                                 

        System.out.println("Text Field Set");                              

        

        // Deleting values in the text box          

        email.clear();               

        password.clear();                    

        System.out.println("Text Field Cleared");                                  

 

        // Find the submit button            

        WebElement login = driver.findElement(By.id("SubmitLogin"));                                             

                              

        // Using click method to submit form        

        email.sendKeys("abcd@gmail.com");                                  

        password.sendKeys("abcdefghlkjl");                                 

        login.click();               

        System.out.println("Login Done with Click");                               

                      

        //using submit method to submit the form. Submit used on password field         

        driver.get(baseUrl);                                

        driver.findElement(By.id("email")).sendKeys("abcd@gmail.com");                                                   

        driver.findElement(By.name("passwd")).sendKeys("abcdefghlkjl");                                                  

        driver.findElement(By.id("SubmitLogin")).submit();                                

        System.out.println("Login Done with Submit");                              

        

               //driver.close();             

                      

    }         

}

 

 

How to Select CheckBox and Radio Button in Selenium WebDriver

Radio Button

Radio Buttons too can be toggled on by using the click() method.

Using http://demo.guru99.com/test/radio.html for practice, see that radio1.click() toggles on the “Option1” radio button. radio2.click() toggles on the “Option2” radio button leaving the “Option1” unselected.



Check Box

Toggling a check box on/off is also done using the click() method.

The code below will click on Facebook’s “Keep me logged in” check box twice and then output the result as TRUE when it is toggled on, and FALSE if it is toggled off.





isSelected() method is used to know whether the Checkbox is toggled on or off.


Here is another example: 
http://demo.guru99.com/test/radio.html


import org.openqa.selenium.By;       

import org.openqa.selenium.WebDriver;        

import org.openqa.selenium.chrome.ChromeDriver;             

import org.openqa.selenium.*;        

 

public class Form {                          

    public static void main(String[] args) {                                                              

              

        // declaration and instantiation of objects/variables       

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

        WebDriver driver = new ChromeDriver();                                     

 

        driver.get("http://demo.guru99.com/test/radio.html");                             

        WebElement radio1 = driver.findElement(By.id("vfb-7-1"));                                                

        WebElement radio2 = driver.findElement(By.id("vfb-7-2"));                                                

                      

        //Radio Button1 is selected          

        radio1.click();                      

        System.out.println("Radio Button Option 1 Selected");                             

                      

        //Radio Button1 is de-selected and Radio Button2 is selected       

        radio2.click();                      

        System.out.println("Radio Button Option 2 Selected");                             

                      

        // Selecting CheckBox        

        WebElement option1 = driver.findElement(By.id("vfb-6-0"));                                               

 

        // This will Toggle the Check box           

        option1.click();                     

 

        // Check whether the Check box is toggled on        

        if (option1.isSelected()) {                                 

            System.out.println("Checkbox is Toggled On");                                 

 

        } else {                     

            System.out.println("Checkbox is Toggled Off");                                

        }             

        

                      

                      

        //Selecting Checkbox and using isSelected Method            

        driver.get("http://demo.guru99.com/test/facebook.html");                                  

        WebElement chkFBPersist = driver.findElement(By.id("persist_box"));                                              

        for (int i=0; i<2; i++) {                                                                                

            chkFBPersist.click ();                  

            System.out.println("Facebook Persists Checkbox Status is -  "+chkFBPersist.isSelected());                                              

        }             

               //driver.close();             

                      

    }         

}

 

How to Click on Image in Selenium Webdriver

Accessing Image Links

Image links are the links in web pages represented by an image which when clicked navigates to a different window or page.

Since they are images, we cannot use the By.linkText() and By.partialLinkText() methods because image links basically have no link texts at all.

In this case, we should resort to using either By.cssSelector or By.xpath. The first method is more preferred because of its simplicity.

In the example below, we will access the “Facebook” logo on the upper left portion of Facebook’s Password Recovery page.


We will use By.cssSelector and the element’s “title” attribute to access the image link. And then we will verify if we are taken to Facebook’s homepage.

package newproject;

import org.openqa.selenium.By;       

import org.openqa.selenium.WebDriver;        

import org.openqa.selenium.chrome.ChromeDriver;             

 

public class MyClass {                       

              

    public static void main(String[] args) {                                                              

        String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";                                

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

        WebDriver driver = new ChromeDriver();                                     

                      

        driver.get(baseUrl);                                

        //click on the "Facebook" logo on the upper left portion           

                       driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();                                

 

                       //verify that we are now back on Facebook's homepage         

                       if (driver.getTitle().equals("Facebook - log in or sign up")) {                                             

            System.out.println("We are back at Facebook's homepage");                                     

        } else {                     

            System.out.println("We are NOT in Facebook's homepage");                              

        }             

                               driver.close();       

 

    }         

}

 

 

Locate Elements by Link Text & Partial Link Text in Selenium Webdriver

What is Link Text in Selenium?

Link Text in Selenium is used to identify the hyperlinks on a web page. It is determined with the help of an anchor tag. For creating the hyperlinks on a web page, we can use an anchor tag followed by the link Text.

Links Matching a Criterion

Links can be accessed using an exact or partial match of their link text. The examples below provide scenarios where multiple matches would exist and would explain how WebDriver would deal with them.

In this tutorial, we will learn the available methods to find and access the Links using Webdriver. Also, we will discuss some of the common problems faced while accessing Links and will further discuss on how to resolve them.

Here is what you will learn-

Accessing links using Exact Text Match: By.linkText()

Accessing links using their exact link text is done through the By.linkText() method. However, if there are two links that have the very same link text, this method will only access the first one. Consider the HTML code below




When you try to run the WebDriver code below, you will be accessing the first “click here” link



import org.openqa.selenium.By;       

import org.openqa.selenium.WebDriver;        

import org.openqa.selenium.chrome.ChromeDriver;             

 

public class MyClass {                       

              

    public static void main(String[] args) {                                                              

        String baseUrl = "http://demo.guru99.com/test/link.html";                                 

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

        WebDriver driver = new ChromeDriver();                                     

                      

        driver.get(baseUrl);                                

        driver.findElement(By.linkText("click here")).click();                                    

        System.out.println("title of page is: " + driver.getTitle());                                                    

        driver.quit();               

    }         

 

}                     

 

 

Comments

Popular posts from this blog

Why to do a POC (Proof Of Concept)