9s. WebDriver – Handling text boxes and images

Hiya testers! If you have been following my posts closely, you should already be a pro in entering text using Selenium WebDriver. If not(with a sad face), nothing to worry! I got you all covered.

Handling text boxes

You might be entering text to two types of input text boxes.

  • The first type is the normal text box that you see in every web page used to enter any information that is being asked. It displays the entered value as it is.
  • And the second type is the password text box where the user types in a value and it is displayed as dots or asterisks or any other special characters for security reasons.

The good news here is, for both these text box types, same command can be used to enter the required value.

Example: Let us enter ‘testFirst’ in the first name and ‘test1234!’ in ‘Create a password’ field.

Explanation: Locate the required elements by id and enter the corresponding values with the sendKeys(“value”) method.

Considering the below code,

<input value="" name="FirstName" id="FirstName" spellcheck="false" type="text">
<input name="Passwd" id="Passwd" type="password">

We can see that the ‘input’ tags have ‘id’ attributes as ‘FirstName’ and ‘Passwd’ for first name and password fields. Once we locate these web elements using their Ids, we will pass ‘testFirst’ and ‘test1234!’ as their respective values.

Code:

driver.findElement(By.id("FirstName")).sendKeys("testFirst");
driver.findElement(By.id("Passwd")).sendKeys("test1234!");

To clear any text that may be present in the text box, clear() method is used. It does not take any arguments.

Output is as below,

Text

Clicking an image

An image can be selected in numerous ways. By id, name, className, cssSelector, xpath etc. Does that ring a bell? I hope it does because locating images can sometimes be very tricky.

Please refer to previous posts on locating elements using various strategies available in WebDriver in case you missed them.

Let us see why this process is tricky with an example scenario.

Example: Navigate to www.amazon.com, and click on the ‘kindle’ image shown on the home page (as on the day this post was created). Upon clicking the image, we should be navigated to the respective page.

Image

Right click on ‘Kindle’ image and Inspect element. Corresponding HTML code is,

<a class="a-link-normal" href="/b/ref=br_pdt_mgUpt?_encoding=UTF8&amp;node=6669702011&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_s=&amp;pf_rd_r=5VQBXJP2N17GX77H0TN9&amp;pf_rd_t=36701&amp;pf_rd_p=9c7b479f-fe0c-48f3-a1ab-c19df6492672&amp;pf_rd_i=desktop">
<img alt="Kindle" 
src="https://images-na.ssl-images-amazon.com/images/G/01/gateway/yiyiz/Kindle._CB300901238_.png" width="292px" height="292px">
</a>

Explanation: As you can notice, there is neither an ‘id’ nor a ‘class’ attribute that is provided with the ‘img’ tag. Thus a teeny weeny bit tricky to locate! And this will be the case for most of the images that you find on the web.

With the HTML code in mind, cssSelector locating strategy can be used. A couple ways to locate the image with this strategy are,

a. Using ‘img’ tag and ‘src’ attribute

driver.findElement(By.cssSelector("img[src='https://images-na.ssl-images-amazon.com/images/G/01/gateway/yiyiz/Kindle._CB300901238_.png']"));

b. Using ‘a’ tag, access its class name with ‘.’ symbol. With a space, specify its child element, ‘img’ tag and ‘src’ attribute

driver.findElement(By.cssSelector("a.a-link-normal img[src='https://images-na.ssl-images-amazon.com/images/G/01/gateway/yiyiz/Kindle._CB300901238_.png']"));

Xpath locating strategy can also be used. A couple ways to locate the image with this strategy are,

a. Using ‘a’ tag with ‘class’ attribute and thereby locating its child element ‘img’

driver.findElement(By.xpath("//a[@class='a-link-normal']/img"));

b. Using ‘img’ tag directly with its ‘src’ attribute

driver.findElement(By.xpath("//img[@src='https://images-na.ssl-images-amazon.com/images/G/01/gateway/yiyiz/Kindle._CB300901238_.png']"));

Scenario under consideration,

  1. Open Firefox browser
  2. Navigate to https://amazon.com
  3. Print the page title to the console
  4. Locate ‘Kindle’ image shown on the home page
  5. Click the image
  6. Print the navigated page title once again to the console
  7. Verify JUnit window for success result in eclipse IDE

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Click_Image {
        //Declaring variables
        private WebDriver driver; 
        private String baseUrl;

        @Before
        public void setUp() throws Exception{
            // Selenium v3 beta releases require system property set up
            System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                   + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
            // Create a new instance for the class FirefoxDriver
            // that implements WebDriver interface
            driver = new FirefoxDriver();
            // Implicit wait for 5 seconds
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            // Assign the URL to be invoked to a String variable
            baseUrl = "https://www.amazon.com/";
        }
        
        @Test
        public void testPageTitle() throws Exception{
            // Open baseUrl in Firefox browser window
            driver.get(baseUrl);
            // Printing page title to console
            System.out.println(driver.getTitle());
            // Locate an image with xpath
            WebElement kindle = driver.findElement(By.cssSelector("img[src='https://images-na.ssl-images-amazon.com/images/G/01/gateway/yiyiz/Kindle._CB300901238_.png']"));
            // Click the image
	    kindle.click();
	    // Printing page title after clicking the image
	    System.out.println("Navigated page title: "+driver.getTitle());        
}
        
         @After
          public void tearDown() throws Exception{
            // Close the Firefox browser
            driver.close();
        }
}

Execution Result:

Code is self-explanatory as comments are provided for every single line.

In JUnit window, green bar shows that the test case is executed successfully. Console window shows the absence of any errors and the page titles before and after the image is clicked.

Image_eclipse_output

Below image shows the Firefox output obtained upon successful execution of the test script.

Image_browser_output

Now it is your turn to experiment with these newly learned skills.

Questions? Fire away in the comments section!

Until then, see you in another post. Have a great day!

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.