Anda di halaman 1dari 11

Web driver tutorials

Content:
1. Java First Program
2. Launch the browser&navigation
 First Test Case with FF Browser
 Running Test on GeckoDriver
 Running Test on Chrome Browser
 Running Test on IE Explorer
3. Browser Package
4. Basic Commands
5. Locators
6. Web elements
7. Explicit Vs Implicit waits
8. User Interactions
 Text Box Interaction
 Radio Button Selection
 Check Box Selection
 Drop Down Item Selection
 Synchronization
 Drag & Drop
 Keyboard actions
 Mouse actions
 Multi Select
 Find all Links
 Web table handling
9. Objects and count of objects
10. Capturing screenshots with Web Driver
11. Handling windows and switching windows (Frame handling)
12. Pop-up and alert handling
13. Keyboard and Mouse event handling
14. Making your own XPath without firebug Dynamic
15. Test Design Techniques
 Page Object Model
 Parameterizing using Excel
 Log4j Logging
 Exception Handling
 Multi Browser Testing
 Capture Screenshots
 Capture Videos
16. TestNG
 Annotations helps us to organize the tests easier.
 Flexible test configuration.
 Test cases can be grouped more easily
 Parallelization of test can be achieved using TestNG
 Support for data-driven testing
 Inbuilt Reporting
17. Selenium Grid

Table of Contents
Java First Program ..................................................................................................................................... 2

Java First Program

Simple Program of Java:


In this page, we will learn how to write the simple program of java. We can write
a simple hello java program easily after installing the JDK. To create a simple java
program, you need to create a class that contains main method. Let's understand the
requirement first.

Requirement for Hello Java Example:


For executing any java program, you need to
• Install the JDK if you don't have installed it, download the JDK and install it.
• Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
• create the java program
• compile and run the java program
• Creating hello java example
Let's create the hello java program:
package first;

publicclass PG1 {
publicstaticvoid main (String []args) {
System.out.println("Hello Java");
}
}
Save this file as Simple.java
To compile: javac Simple.java
To execute: java Simple

1. Launch the browser & navigation


 First Test Case with FF Browser (selenium-server-standalone-2.42.2)
Below is the simple program for launch the Firefox browse with navigate to google.

package first;

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

publicclass LaunchFF {
publicstaticvoid main (String []args) {
WebDriver driverff = new FirefoxDriver();
driverff.get("https://google.com");
}
}

 Running Test on GeckoDriver


Below is the simple program for launch the GeckoDriverbrowse with navigate to google.

package first;

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

publicclass Launchgecko {
publicstaticvoid main (String []args) {
System.setProperty("webdriver.firefox.marionette",
"D:\\driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://google.com");
}
}

 Running Test on Chrome Browser


Below is the simple program for launch the chrome browse with navigate to google.

package first;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

publicclass LaunchChrome {
publicstaticvoid main (String []args) {
System.setProperty("webdriver.chrome.driver", "D:\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
}
}

 Running Test on IE Browser


Below is the simple program for launch the IE browse with navigate to google.
package first;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

publicclass LaunchIE {
publicstaticvoid main(String[] args) {
System.setProperty("webdriver.ie.driver","D:\\driver\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
driver.get("http://google.com");
}
}

2. Importing Packages
To get started, you need to import following two packages:
org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new browser
loaded with a specific driver
org.openqa.selenium.firefox.FirefoxDriver - contains the FirefoxDriver class needed to
instantiate a Firefox-specific driver onto the browser instantiated by the WebDriver class.
org.openqa.selenium.firefox.ChromeDriver - contains the ChromeDriver class needed to
instantiate a Chrome-specific driver onto the browser instantiated by the WebDriver class.
org.openqa.selenium.firefox.InternetExplorerDriver- contains the Internet Explorer Driver
class needed to instantiate anInternet explorer-specific driver onto the browser instantiated
by the WebDriver class.

If your test needs more complicated actions such as accessing another class, taking browser
screenshots, or manipulating external files, definitely you will need to import more
packages.
3. Basic Commands
1.Get Commands
Get commands fetch various important information about the page/element. Here are
some important "get" commands you must be familiar with.

Command Command Category


driver.get() 1. It automatically opens a new browser window and fetches the page that
you specify inside its parentheses.
2. It is the counterpart of Selenium IDE's "open" command.
3. The parameter must be a String object.
driver.getTitle() 1. Needs no parameters
2.Fetches the title of the current page
3.Leading and trailing white spaces are trimmed
4. Returns a null string if the page has no title.
driver.getPageSource() 1. Needs no parameters
2.Returns the source code of the page as a String value.
driver.getCurrentUrl() 1. Needs no parameters
2.Fetches the string representing the current URL that the browser is
looking at.
driver.getText() 1. Fetches the inner text of the element that you specify.

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

Command Command Category


driver.navigate().to() 1. It automatically opens a new browser window and fetches the
page that you specify inside its parentheses.
2. It does exactly the same thing as the get() method.
driver.navigate().refresh() 1. Needs no parameters.
2. It refreshes the current page.
driver.navigate().back() 1.Needs no parameters
2.Takes you back by one page on the browser's history.
driver.navigate().forward() 1.Needs no parameters
2.Takes you forward by one page on the browser's history.

3. Closing and Quitting Browser Windows


These commands allow you to closes only the browser and closes all windows.

Command Command Category


driver.close(); 1. Needs no parameters
2.It closes only the browser window that WebDriver is currently
controlling.
driver.quit(); 1. Needs no parameters.
2.It closes all windows that WebDriver has opened.

Practice Exercise – 1
1. Launch a new browser.
2. Open Store.DemoQA.com
3. Get Page Title name and Title length
4. Print Page Title and Title length on the Eclipse Console.
5. Get Page URL and verify if the it is a correct page opened
6. Get Page Source (HTML Source code) and Page Source length
7. Print Page Length on Eclipse Console.
8. Close the Browser.
package first;

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

publicclass WebDriverCommands_1 {
publicstaticvoid main(String []args) {
System.setProperty("webdriver.chrome.driver",
"D:\\driver\\chromedriver.exe");

//Launch a new Chrome browser


WebDriver driver = new ChromeDriver();

//Open Store.DemoQA.com
String url = "http://store.demoqa.com/";
driver.navigate().to(url);

//Get Page Title name and Title length


String title = driver.getTitle();
inttitlelength = driver.getTitle().length();

//Print the output in Eclipse console


System.out.println("The title of the broswer is:"+title);
System.out.println("The title of the broswer is:"+titlelength);

//verify if the it is a correct page opened


String actualUrl = driver.getCurrentUrl();
if (actualUrl.equals(url))
{
System.out.println("Verification Successful");
}
else
{
System.out.println("Verification Failed");
}

//Get Page Source (HTML Source code) and Page Source length
String pageSource = driver.getPageSource();

//Storing Page Source length in Int variable


intpageSourceLength = pageSource.length();

// Printing length of the Page Source on console


System.out.println("Total length of the Page Source is: " +
pageSourceLength);

//Closing browser
driver.close();
}
}
Output
Title of the page is : ONLINE STORE | Toolsqa Dummy Test site
Length of the title is : 38
Verification Failed – An incorrect Url is opened.
Total length of the Page Source is: 35646

Practice Exercise-2
1. Launch new Browser
2. Open DemoQA.com website
3. Click on Registration link using “driver.findElement(By.xpath(“.//*[@id=’menu-item-
374′]/a”)).click();“
4. Come back to Home page (Use ‘Back’ command)
5. Again go back to Registration page (This time use ‘Forward’ command)
6. Again come back to Home page (This time use ‘To’ command)
7. Refresh the Browser (Use ‘Refresh’ command)
8. Close the Browser
package first;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

publicclass WebDriverCommands_2 {
publicstaticvoid main(String []args) {
System.setProperty("webdriver.chrome.driver",
"D:\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "http://demoqa.com/";
driver.navigate().to(url);
driver.findElement(By.xpath(".//*[@id='nav_menu-6']/div[1]/h3")).click();
driver.navigate().back();
driver.navigate().forward();
driver.navigate().to(url);
driver.navigate().refresh();
driver.close();
System.out.println("Completed");
}
}

4. Locators
Locating elements in Selenium WebDriver is performed with the help of findElement() and
findElements() methods provided by WebDriver and WebElement class.
 findElement() returns a WebElement object based on a specified search criteria or ends
up throwing an exception if it does not find any element matching the search criteria.
 findElements() returns a list of WebElements matching the search criteria. If no
elements are found, it returns an empty list.
The following table lists all the Java syntax for locating elements in Selenium WebDriver.

Method Syntax Description


By Id driver.findElement(By.id(<element ID>)) Locates an element using the
ID attribute
By name driver.findElement(By.name(<element name>)) Locates an element using the
Name attribute
By driver.findElement(By.className(<element Locates an element using the
classname class>)) Class attribute
By tagname driver.findElement(By.tagName(<htmltagname>)) Locates an element using the
HTML tag
By linkText driver.findElement(By.linkText(<linktext>)) Locates a link using link text
Bypartiallink driver.findElement(By.partialLinkText(<linktext>)) Locates a link using the link's
text partial text
By CSS driver.findElement(By.cssSelector(<css selector>)) Locates an element using the
CSS selector
ByXPath driver.findElement(By.xpath(<xpath>)) Locates an element using
XPath query

5. Locator Usage
Now let us understand the practical usage of each of the locator methods with the help of
http://www.calculator.net
a. By ID:
Here an object is accessed with the help of IDs. In this case, it is the ID of the text box.
Values are entered into the text box using the sendkeys method with the help of
ID(cdensity).
driver.findElement(By.id("cdensity")).sendKeys("10");
b. By Name:
Here an object is accessed with the help of names. In this case, it is the name of the text
box. Values are entered into the text box using the sendkeys method with the help of
ID(cdensity).
driver.findElement(By.name("cdensity")).sendKeys("10");
c. By Class Name
Here an object is accessed with the help of Class Names. In this case, it is the Class name of
the WebElement. The Value can be accessed with the help of the gettext method.
List<WebElement> byclass = driver.findElements(By.className("smalltext smtb"));
d. By Tag Name
The DOM Tag Name of an element can be used to locate that particular element in the
WebDriver. It is very easy to handle tables with the help of this method. Take a look at the
following code.
WebElement table = driver.findElement(By.id("calctable"));
List<WebElement> row = table.findElements(By.tagName("tr"));
int rowcount = row.size();

e. By Link Text
This method helps to locate a link element with matching visible text.
driver.findElements(By.linkText("Volume")).click();
f. By partial link text
This methods helps locate a link element with partial matching visible text.
driver.findElements(By.partialLinkText("Volume")).click();
g. By CSS
The CSS is used as a method to identify the webobject, however NOT all browsers support
CSS identification.
WebElement loginButton = driver.findElement(By.cssSelector("input.login"));
h. By XPath
XPath stands for XML path language. It is a query language for selecting nodes from an XML
document. XPath is based on the tree representation of XML documents and provides the
ability to navigate around the tree by selecting nodes using a variety of criteria.
driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td
[1]/input")).sendkeys("100");

Practice Exercise – 3
1. Launch a new Firefox browser.
2. Open http://demoqa.com/frames-and-windows/
3. Maximize the browser
4. Use this statement to click on a New Window button
“driver.findElement(By.xpath(“.//*[@id=’tabs-1′]/div/p/a”)).click();”
5. Close the browser using close() command
You will notice that only one window will close. Next time use quit() command instead of
close(). At that time selenium will close both the windows.
package first;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

publicclass WebDriverCommands_3 {
publicstaticvoid main (String []args)
{
String link "D:\\driver\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", link);
WebDriver driver = new ChromeDriver();
String url = "http://demoqa.com/frames-and-windows/";
driver.manage().window().maximize();
driver.navigate().to(url);
driver.findElement(By.xpath(".//*[@id='tabs-1']/div/p/a")).click();
System.out.println("Successfully find Xpath" );
driver.close();
}
}

Practice Exercise – 4
1. Launch a new Chrome browser.
2. Open http://www.calculator.net/
3. Maximize the browser
4. Click on BMI calculator and provide the values using Web driver locators
5. Print the results in Eclipse console
6. Close the browser

http://toolsqa.com/selenium-webdriver/browser-navigation-commands/
http://www.guru99.com/first-webdriver-script.html
http://compalg.inf.elte.hu/~attila/materials/Webdriver_Java_2015.pdf
https://www.tutorialspoint.com/selenium/selenium_webdriver.htm

Anda mungkin juga menyukai