Friday, November 14, 2014

On 6:03 AM by Unknown in    No comments
Locating GUI Elements

Locating elements in WebDriver is done by using the “findElement(By.locator())” method. The “locator” part of the code is same as any of the locators previously discussed in the Selenium IDE chapters of these tutorials. In fact, it is recommended you locate GUI elements using IDE and once successfully identified export the code to webdriver.

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

package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public static void main(String[] args) {
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);
}
}
We used the getTagName() method to extract the tag name of that particular element whose id is “email”. When run, this code should be able to correctly identify the tag name “input” and will print it out on Eclipse’s Console window.

21

Summary for locating elements
















































VariationDescriptionSample
By.classNamefinds elements based on the value of the “class” attributefindElement(By.className(“someClassName”))
By.cssSelectorfinds elements based on the driver’s underlying CSS Selector enginefindElement(By.cssSelector(“input#email”))
By.idlocates elements by the value of their “id” attributefindElement(By.id(“someId”))
By.linkTextfinds a link element by the exact text it displaysfindElement(By.linkText(“REGISTRATION”))
By.namelocates elements by the value of the “name” attributefindElement(By.name(“someName”))
By.partialLinkTextlocates elements that contain the given link textfindElement(By.partialLinkText(“REG”))
By.tagNamelocates elements by their tag namefindElement(By.tagName(“div”))
By.xpathlocates elements via XPathfindElement(By.xpath(“//html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]

/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[5]”))

 

Note on Using findElement(By.cssSelector())

By.cssSelector() does not support the “contains” feature. Consider the Selenium IDE code below -

22

In Selenium IDE above, the entire test passed. However in the WebDriver script below, the same test generated an error because WebDriver does not support the “contains” keyword when used in the By.cssSelector() method.

23

 

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.

WebElement myElement = driver.findElement(By.id("username"));
myElement.sendKeys("Tutorial");
 
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 example shows how click() was used to click on Mercury Tours’  “Sign-In” button.

driver.findElement(By.name("Login")).click();
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.























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 parametersFetches the title of the current pageLeading and trailing white spaces are trimmedReturns a null string if the page has no title
getPageSource()Sample usage:Needs no parametersReturns the source code of the page as a String value
getCurrentUrl()Sample usage:Needs no parametersFetches 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 parametersTakes you back by one page on the browser’s history.
navigate().forward()Sample usage:Needs no parametersTakes you forward by one page on the browser’s history.

 

Closing and Quitting Browser Windows











close()Sample usage:Needs no parametersIt closes only the browser window that WebDriver is currently controlling.
quit()Sample usage:Needs no parametersIt closes all windows that WebDriver has opened.

25

To clearly illustrate the difference between close() and quit(), try to execute the code below. It uses a webpage that automatically pops up a window upon page load and opens up another after exiting.

close

Notice that only the parent browser window was closed and not the two pop-up windows.

26

But if you use quit(), all windows will be closed – not just the parent one. Try running the code below and you will notice that the two pop-ups above will automatically be closed as well.
package mypackage;

import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver;

public class myclass {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver(); 
driver.get("http://www.popuptest.com/popuptest2.html");
driver.quit(); // using QUIT all windows will close
}

}

Switching Between Frames

To access GUI elements in a Frame, we should first direct WebDriver to focus on the frame or pop-up window first before we can access elements within them. Let us take, for example, the web page http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html

27

 

This page has 3 frames whose “name” attributes are indicated above. We wish to access the “Deprecated” link encircled above in yellow. In order to do that, we must first instruct WebDriver to switch to the “classFrame” frame using the “switchTo().frame()” method. We will use the name attribute of the frame as the parameter for the “frame()” part.
package mypackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myclass {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.get("http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html");
driver.switchTo().frame("classFrame");
driver.findElement(By.linkText("Deprecated")).click();
driver.quit();

}

}

After executing this code, you will see that the “classFrame” frame is taken to the “Deprecated API” page, meaning that our code was successfully able to access the “Deprecated” link.

Switching Between Pop-up Windows

WebDriver allows pop-up windows like alerts to be displayed, unlike in Selenium IDE. To access the elements within the alert (such as the message it contains), we must use the “switchTo().alert()” method. In the code below, we will use this method to access the alert box and then retrieve its message using the “getText()” method, and then automatically close the alert box using the “switchTo().alert().accept()” method.

First,  head over to http://jsbin.com/usidix/1 and manually click the “Go!” button there and see for yourself the message text.

28

Lets see the WebDriver code to do this-
package mypackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myclass {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
String alertMessage = "";
driver.get("http://jsbin.com/usidix/1");
driver.findElement(By.cssSelector("input[value=\"Go!\"]")).click();
alertMessage = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alertMessage);
driver.quit();
}

}

On the Eclipse console, notice that the printed alert message is:

29

Waits

There are two kinds of waits.

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

  • 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.

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


30


Explicit Wait

Explicit waits are done using the WebDriverWait and Expected-condition classes. For the following 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:

sa

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

31

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.

32

 

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.

33


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

34


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.

35


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.

36

elementToBeClickable() – waits until an element is visible and, at the same time, enabled. The sample 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”.

37

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

38


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”.

39

 

Summary

  • To start using the WebDriver API, you must import at least these two packages.

    • openqa.selenium.*

    • openqa.selenium.firefox.FirefoxDriver



  • The following are the available options for locating elements in WebDriver:

    • className

    • cssSelector

    • id

    • linkText

    • name

    • partialLinkText

    • tagName

    • xpath



  • Locating elements in WebDriver is done by using the findElement(By()) method.

  • The get() method is the equivalent of Selenium IDE’s “open” command.

  • TheBy.cssSelector() does not support the “contains” feature.

  • You can instantiate an element using the WebElement class.

  • Clicking on an element is done by using the click() method.

  • WebDriver provides these useful get commands:

    • get()

    • getTitle()

    • getPageSource()

    • getCurrentUrl()

    • getText()



  • WebDriver provides these useful navigation commands

    • navigate().forward()

    • navigate().back()

    • navigate().to()

    • navigate().refresh()



  • The close() and quit() methods are used to close browser windows. Close() is used to close a single window; while quit() is used to close all windows associated to the parent window that the WebDriver object was controlling.

  • The switchTo().frame() and switchTo().alert() methods are used to direct WebDriver’s focus onto a frame or alert, respectively.

  • Implicit waits are used to set the waiting time throughout the program, while explicit waits are used only on specific portions.

  • You can use the isEnabled(), isDisplayed(),isSelected(), and a combination of WebDriverWait and ExpectedConditions methods when verifying the state of an element. However, they do not verify if the element exists.

  • When isEnabled(), isDisplayed(),or isSelected() was called while the element was not existing, WebDriver will throw a NoSuchElementException.

  • When WebDriverWait and ExpectedConditions methods were called while the element was not existing, WebDriver would throw a TimeoutException.


Accessing Forms in WebDriver

Here, we will learn how to access forms and its  elements using Webdriver

Accessing Form Elements

  • Input Box

  • Input boxes refer to either of these two types:

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

  • 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.


40

Entering Values in Input Boxes

The sendKeys() method is used to enter values into input boxes.Entering Values in Input Boxes.

41

Deleting Values in Input Boxes

The clear() method is used to delete the text in an input box. This method does not need any parameter. The code snippet below will clear out the text “tutorial” in the User Name text box.

42

 

Radio Button

Toggling a radio button on is done using the click() method.

43

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.

44

45

 

Links

Links also are accessed by using the click() method.

Consider the below link found in Mercury Tours’ homepage.

46

You can access this link using linkText() or partialLinkText() together with click(). Either of the two lines below will be able to access the “Register here” link shown above.

47

48

 

Drop-Down Box

Before we can control drop-down boxes, we must do following two things :

  • Import the package org.openqa.selenium.support.ui.Select

  • Instantiate the drop-down box as a “Select” object in WebDriver


As an example, go to Mercury Tours’ Registration page (http://newtours.demoaut.com/mercuryregister.php) and notice the “Country” drop-down box there.

49

Step 1 - Import the “Select” package.

50

Step 2 - Declare the drop-down element as an instance of the Select class. In the example below, we named this instance as “drpCountry”.

51

 

Step 3 - We can now start controlling “drpCountry” by using any of the available Select methods. The sample code below will select the option “ANTARCTICA”.

52

Selecting Items in a Multiple SELECT element

We can also use the selectByVisibleText() method in selecting multiple options in a multi SELECT element. As an example, we will take http://jsbin.com/osebed/2 as the base URL. It contains a drop-down box that allows multiple selections at a time.

53

The code below will select the first two options using the selectByVisibleText() method.

54

Select Methods

The following are the most common methods used on drop-down elements.



























MethodDescription
selectByVisibleText() and

deselectByVisibleText()

Example: drpcountry.selectByVisibleText("Antarctica")'
Selects/deselects the option that displays the text matching the parameter.

Parameter: The exactly displayed text of a particular option
selectByValue() and

deselectByValue()

Example: drpcountry.selectByValue("234");
Selects/deselects the option whose “value” attribute matches the specified parameter.

Parameter: value of the “value” attribute

Remember that not all drop-down options have the same text and “value”, like in the example below.

55

 
selectByIndex() and

deselectByValue()

Example: drpcountry.selectByIndex(0);

 
Selects/deselects the option at the given index.

Parameter: the index of the option to be selected.
isMultiple()

Example:

if(drpcountry.isMultiple()){

// do something here

}

 
Returns TRUE if the drop-down element allows multiple selections at a time; FALSE if otherwise.

Needs parameters needed
deselectAll()

Example: drpcountry.deselectAll();

 
Clears all selected entries. This is only valid when the drop-down element supports multiple selections.

No parameters needed

 

Submitting a Form

  • The submit() method is used to submit a form. This is an alternative to clicking the form’s submit button.

  •  You can use submit() on any element within the form, not just on the submit button itself.


56

 

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

Summary

The table below summarizes the commands to access each type of element discussed above.





















































ElementCommandDescription
Input BoxsendKeys()used to enter values onto text boxes
clear()used to clear text boxes of its current value
Check Box,

Radio Button,

 
click()used to toggle the element on/off
Linksclick()used to click on the link and wait for page load to complete before proceeding to the next command.
Drop-Down BoxselectByVisibleText()/

deselectByVisibleText()
selects/deselects an option by its displayed text
selectByValue()/

deselectByValue()
selects/deselects an option by the value of its “value” attribute
selectByIndex()/

deselectByIndex()
selects/deselects an option by its index
isMultiple()returns TRUE if the drop-down element allows multiple selection at a time; FALSE if otherwise
deselectAll()deselects all previously selected options
Submit Buttonsubmit()


  • WebDriver allows selection of more than one option in a multiple SELECT element.

  • To control drop-down boxes, you must first import the org.openqa.selenium.support.ui.Select package and then create a Select instance.

  • You can use the submit() method on any element within the form. WebDriver will automatically trigger the submit function of the form where that element belongs to.


 

 

Accessing Links & Tables 

Now we will learn about accessing links & Tables using Webdriver

Accessing Links

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.

Exact Match

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

57

 

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

58

As a result, you will automatically be taken to Google.

59

 

Partial Match

Accessing links using a portion of their link text is done using the By.partialLinkText() method. If you specify a partial link text that has multiple matches, only the first match will be accessed. Consider the HTML code below.

60

61

When you execute the WebDriver code below, you will still be taken to Google.

62

63

Case-sensitivity

The parameters for By.linkText() and By.partialLinkText() are both case-sensitive, meaning that capitalization matters. For example, in Mercury Tours’ homepage, there are two links that contain the text “egis” – one is the “REGISTER” link found at the top menu, and the other is the “Register here” link found at the lower right portion of the page.

64

Though both links contain the character sequence “egis”, the "By.partialLinkText()" method will access these two links separately depending on capitilization of the characters. See the sample code below.

65

All Links

One of the common procedures in web testing is to test if all the links present within the page are working. This can be conveniently done using a combination of the Java for-each loop and the By.tagName(“a”) method. The WebDriver code below checks each link from the Mercury Tours homepage to determine those that are working and those that are still under construction.

 
package practice_webdriver;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AllLinks {

public static void main(String[] args) {

String baseUrl = "http://newtours.demoaut.com/";
WebDriver driver = new FirefoxDriver();
String underConsTitle = "Under Construction: Mercury Tours";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(baseUrl);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
String[] linkTexts = new String[linkElements.size()];
int i = 0;

//extract the link texts of each link element
for (WebElement e : linkElements) {
linkTexts[i] = e.getText();
i++;
}

//test each link
for (String t : linkTexts) {
driver.findElement(By.linkText(t)).click();

if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""
+ " is working.");
}
driver.navigate().back();
}
driver.quit();
}
}

The output should be similar to the one indicated below.

66

Links Outside and Inside a Block

The latest HTML5 standard allows the <a> tags to be placed inside and outside of block-level tags like <div>, <p>, or <h1>. The "By.linkText()" and "By.partialLinkText()" methods can access a link located outside and inside these block-level elements. Consider the HTML code below.

67

68

The WebDriver code below accesses both of these links using By.partialLinkText() method.

69


The output above confirms that both links were accessed successfully because their respective page titles were retrieved correctly.

Accessing Image Links

Image links are images that act as references to other sites or sections within the same 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.

70

 

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 practice_webdriver;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ImageLink {

public static void main(String[] args) {

String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
WebDriver driver = new FirefoxDriver();
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("Welcome to Facebook - Log In, Sign Up or Learn More")) {
System.out.println("We are back at Facebook's homepage");
} else {
System.out.println("We are NOT in Facebook's homepage");
}
driver.quit();
}
}

 

Result

71

 

Reading a Table

There are times when we need to access elements (usually texts) that are within HTML tables. However, it is very seldom for a web designer to provide an id or name attribute to a certain cell in the table. Therefore, we cannot use the usual methods such as “By.id()”, “By.name()”, or “By.cssSelector()”. In this case, the most reliable option is to access them using the “By.xpath()” method.

XPath Syntax

Consider the HTML code below.

72

We will use XPath to get the inner text of the cell containing the text “fourth cell”.

73

Step 1 – Set the Parent Element (table)

XPath locators in WebDriver always start with a double forward slash “//” and then followed by the parent element. Since we are dealing with tables, the parent element should always be the <table> tag. The first portion of our XPath locator should therefore start with “//table”.

74

Step 2 – Add the child elements

The element immediately under <table> is <tbody> so we can say that <tbody> is the “child” of <table>. And also, <table> is the “parent” of <tbody>. All child elements in XPath are placed to the right of their parent element, separated with one forward slash “/” like the code shown below.

75        76

 

Step 3 – Add Predicates

The <tbody> element contains two <tr> tags. We can now say that these two <tr> tags are “children” of <tbody>. Consequently, we can say that <tbody> is the parent of both the <tr> elements.

Another thing we can conclude is that the two <tr> elements are siblings. Siblings refer to child elements having the same parent.

To get to the <td> we wish to access (the one with the text “fourth cell”), we must first access the second <tr> and not the first. If we simply write “//table/tbody/tr”, then we will be accessing the first <tr> tag.

So, how do we access the second <tr> then? The answer to this is to use Predicates.

Predicates are numbers or HTML attributes enclosed in a pair of square brackets “[ ]” that distinguish a child element from its siblings. Since the <tr> we need to access is the second one, we shall use “[2]” as the predicate.

77

If we won’t use any predicate, XPath will access the first sibling. Therefore, we can access the first <tr> using either of these XPath codes.

78

Step 4 – Add the Succeeding Child Elements Using the Appropriate Predicates

The next element we need to access is the second <td>. Applying the principles we have learned from steps 2 and 3, we will finalize our XPath code to be like the one shown below.

79

Now that we have the correct XPath locator, we can already access the cell that we wanted to and obtain its inner text using the code below. It assumes that you have saved the HTML code above as “newhtml.html” within your C Drive.

80

81

 

Accessing Nested Tables

The same principles discussed above applies to nested tables. Nested tables are tables located within another table. An example is shown below.

82

83

To access the cell with the text “4-5-6” using the “//parent/child” and predicate concepts from the previous section, we should be able to come up with the XPath code below.

84

 

The WebDriver code below should be able to retrieve the inner text of the cell which we are accessing.

85

The output below confirms that the inner table was successfully accessed.

86

Using Attributes as Predicates

If the element is written deep within the HTML code such that the number to use for the predicate is very difficult to determine, we can use that element’s unique attribute instead.

In the example below, the “New York to Chicago” cell is located deep into Mercury Tours homepage’s HTML code.

87

88

 

In this case, we can use the table’s unique attribute (width=”270”) as the predicate. Attributes are used as predicates by prefixing them with the @ symbol. In the example above, the “New York to Chicago” cell is located in the first <td> of the fourth <tr>, and so our XPath should be as shown below.

Remember that when we put the XPath code in Java, we should use the escape character backward slash “\” for the double quotation marks on both sides of “270” so that the string argument of By.xpath() will not be terminated prematurely.

90

We are now ready to access that cell using the code below.

91

 

92

 

Shortcut: Use Firebug

If the number or attribute of an element is extremely difficult or impossible to obtain, the quickest way to generate the XPath code is thru Firebug.

Consider the example below from Mercury Tours homepage.

93

Step 1- Use Firebug to obtain the XPath code.

94

 

Step 2 - Look for the first “table” parent element and delete everything to the left of it.

95

Step 3 - Prefix the remaining portion of the code with double forward slash “//” and copy it over to your WebDriver code.

96

The WebDriver code below will be able to successfully retrieve the inner text of the element we are accessing.

97

Summary

  • Accessing links using their exact match is done using By.linkText() method.

  • Accessing links using their partial match is done using By.partialLinkText() method.

  • If there are multiple matches, By.linkText() and By.partialLinkText() will only select the first match.

  • Pattern matching using By.linkText() and By.partialLinkText() is case-sensitive.

  • The By.tagName("a") method is used to fetch all links within a page.

  • Links can be accessed by the By.linkText() and By.partialLinkText() whether they are inside or outside block-level elements.

  • Accessing image links are done using By.cssSelector() and By.xpath() methods.

  • By.xpath() is commonly used to access table elements.


 
Keyboard Mouse Events, Uploading Files - Webdriver

Now we will learn handling keyboard and mouse in Webdriver and deal with file uploads and downloads

Handling Keyboard & Mouse Events

98Handling special keyboard and mouse events are done using the Advanced User Interactions API. It contains the Actions and the Action classes that are needed when executing these events. The following are the most commonly used keyboard and mouse events provided by the Actions class.Handling Keyboard & Mouse Events



















































MethodDescription
clickAndHold()Clicks (without releasing) at the current mouse location.
contextClick()Performs a context-click at the current mouse location.
doubleClick()Performs a double-click at the current mouse location.
dragAndDrop(source, target)Performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.

Parameters:

source- element to emulate button down at.

target- element to move to and release the mouse at.
dragAndDropBy(source, x-offset, y-offset)Performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.

Parameters:

source- element to emulate button down at.

xOffset- horizontal move offset.

yOffset- vertical move offset.
keyDown(modifier_key)Performs a modifier key press. Does not release the modifier key - subsequent interactions may assume it's kept pressed.

Parameters:

modifier_key – any of the modifier keys (Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
keyUp(modifier _key)Performs a key release.

Parameters:

modifier_key – any of the modifier keys (Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
moveByOffset(x-offset, y-offset)Moves the mouse from its current position (or 0,0) by the given offset.

Parameters:

x-offset- horizontal offset. A negative value means moving the mouse left.

y-offset- vertical offset. A negative value means moving the mouse up.
moveToElement(toElement)Moves the mouse to the middle of the element. Parameters:

toElement- element to move to.
release()Releases the depressed left mouse button at the current mouse location
sendKeys(onElement, charsequence)Sends a series of keystrokes onto the element. Parameters:

onElement - element that will receive the keystrokes, usually a text field

charsequence – any string value representing the sequence of keystrokes to be sent

 

In the following example, we shall use the moveToElement() method to mouse-over on one Mercury Tours’ table rows. See the example below.

99

The cell shown above is a portion of a <TR> element. If not hovered, its color is #FFC455 (orange). After hovering, the cell’s color becomes transparent. It becomes the same color as the blue background of the whole orange table.

Step 1 - Import the Actions and Action classes.

100

Step 2 - Instantiate a new Actions object.

101

Step 3 - Instantiate an Action using the Actions object in step 2.

102

In this case, we are going to use the moveToElement() method because we are simply going to mouse-over the “Home” link. The build() method is always the final method used so that all the listed actions will be compiled into a single step.

Step 4 - Use the perform() method when executing the Action object we designed in Step 3.

103

Below is the whole WebDriver code to check the background color of the <TR> element before and after the mouse-over.
package mypackage;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class myclass {

public static void main(String[] args) {

String baseUrl = "http://newtours.demoaut.com/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement link_Home = driver.findElement(By.linkText("Home"));
WebElement td_Home = driver.findElement(By.xpath("//html/body/div"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr"));

Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(link_Home)
.build();
String bgColor = td_Home.getCssValue("background-color");
System.out.println("Before hover: " + bgColor);
mouseOverHome.perform();
bgColor = td_Home.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
driver.quit();
}
}

 

 

The output below clearly states that the background color became transparent after the mouse-over.

104

Building a Series of Multiple Actions

You can build a series of actions using the Action and Actions classes. Just remember to close the series with the build() method. Consider the sample code below.

105

106

 

Uploading Files

For this section, we will use http://www.megafileupload.com/ as our test application. This site easily allows any visitor to upload and download files without requiring them to sign up.

Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select input field to enter the path to the file to be uploaded.

107

Let’s say we wish to upload the file “C:\newhtml.html”. Our WebDriver code should be like the one shown below.
package mypackage;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myclass {

public static void main(String[] args) {

String baseUrl = "http://www.megafileupload.com/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement uploadElement = driver.findElement(By.id("uploadfile_0"));

// enter the file path onto the file-selection input field
uploadElement.sendKeys("C:\\newhtml.html");

// check the "I accept the terms of service" check box
driver.findElement(By.id("terms")).click();

// click the "UploadFile" button
driver.findElement(By.name("send")).click();
}
}

 

After running this script, you should be able to upload the file successfully and you should get a message similar to this.

108

Remember following two things when uploading files in WebDriver

There is no need to simulate the clicking of the “Browse” button.  WebDriver automatically enters the file path onto the file-selection text box of the <input type=”file”> element

When setting the file path in your Java IDE, use the proper escape character for the back-slash.

109

Downloading Files

WebDriver has no capability to access the Download dialog boxespresented by browsers when you click on a download link or button. However, we can bypass these dialog boxes using a separate program called “wget”.

What is Wget?

Wget is a small and easy-to-use command-line program used to automate downloads. Basically, we will access Wget from our WebDriver script to perform the download process.

Setting up Wget

Step 1 - In your C Drive, create a new folder and name it as “Wget”.

Download wget.exe here and place it in the Wget folder you created from the step above.

Step 2 - Bring up the System Properties window by pressing Win + Pause on your keyboard.

Click on “Advanced System Settings”.

110

Click on the “Environment Variables”.

111

Step 3 - In the Environment Variables dialog box, in the “System variables” section, scroll down the list until you find “Path” and then double-click it.

112

Step 4 - In the “Variable value” text box, add the new path “C:\Wget\”. Just be sure that there is a semi-colon separating this new entry from the preexisting values.

113

Step 5 - Click OK on all dialog boxes.

Launch the command prompt and type the command “wget”. You should get the following response.

114

Using WebDriver and Wget

In the following example, we will use WebDriver and wget to download a popular chat software called Yahoo Messenger. Our base URL shall be http://messenger.yahoo.com/.

115

Step 1 - Import the “java.io.IOException” package because we will have to catch an IOException later in Step 4.

116

Step 2 - Use getCssAttribute() to obtain the “href” value of the download link and save it as a String variable. In this case, we named the variable as “sourceLocation”.

117

Step 3 - Set-up the syntax for wget using the following command.

118

Step 4 - Initiate the download process by calling wget from our WebDriver code.

119

To sum it all up, your WebDriver code could look like the one shown below.
package mypackage;

import java.io.IOException;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myclass {

public static void main(String[] args) {

String baseUrl = "http://messenger.yahoo.com/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement downloadButton = driver.findElement(By.id("messenger-download"));
String sourceLocation = downloadButton.getAttribute("href");
String wget_command = "cmd /c wget -P c: " + sourceLocation;
try {
Process exec = Runtime.getRuntime().exec(wget_command);
int exitVal = exec.waitFor();
System.out.println("Exit value: " + exitVal);
} catch (InterruptedException | IOException ex) {
System.out.println(ex.toString());
}
driver.quit();
}
}

After executing this code, check your C drive and verify that the Yahoo Messenger installer was successfully downloaded there.

120

 

Summary

  • Handling special keyboard and mouse events are done using the AdvancedUserInteractions API.

  • Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select input field to enter the path to the file to be uploaded.

  • WebDriver cannot automate downloading of files on its own.

  • The eaasiest way to download files using WebDriver is to use Wget.

0 comments:

Post a Comment