Monday 2 May 2016

Keyboard Mouse Events , Uploading Files - Webdriver



Method
Description
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.
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.
Step 2
Instantiate a new Actions object.
Step 3
Instantiate an Action using the Actions object in step 2.
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.
Below is the whole WebDriver code to check the background color of the <TR> element before and after the mouse-over.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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.

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.

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.
Let's say we wish to upload the file "C:\newhtml.html". Our WebDriver code should be like the one shown below.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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.
Remember following two things when uploading files in WebDriver
  1. 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
  2. When setting the file path in your Java IDE, use the proper escape character for the back-slash.

Downloading Files

WebDriver has no capability to access the Download dialog boxes presented 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".
Click on the "Environment Variables".
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.
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 pre-existing values.
Step 5
Click OK on all dialog boxes.
Launch the command prompt and type the command "wget". You should get the following response.

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/.
Step 1
Import the "java.io.IOException" package because we will have to catch an IOException later in Step 4.
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".
Step 3
Set-up the syntax for wget using the following command.
Step 4
Initiate the download process by calling wget from our WebDriver code.
To sum it all up, your WebDriver code could look like the one shown below.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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: --no-check-certificate " + 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.

1 comment: