Selenium Web driver
1.
What is selenium webdriver and how it help us in software testing process?
Webdriver in selenium (http://docs.seleniumhq.org/projects/webdriver/) is an Interface and it is
designed to overcome some limitations of selenium RC software testing tool. However selenium
WebDriver's development is in process so still there are few limitations and known issues available
in selenium WebDriver. Selenium WebDriver is also known as Selenium 2 and used for web as well
mobile
applications testing. It is freeware software testing tool and mostly used as a regression testing tool
for web and mobile applications.
Selenium 2 supports most of all browsers to run your test cases and many programming languages
like C#, Java, Python, Ruby, .Net, Perl, PHP, etc.. to create and modify your test scripts. Selenium
2(WebDriver) controls browser directly from operating system level so it is interacting very fast and
with more realistic way with browsers. Major people in world using Selenium webdriver with java.
2.
Difference between WebDriver and selenium RC
WebDriver
Selenium WebDriver do not require selenium server for running test.
WebDriver is using native automation from each and every supported language for running
automation scripts on browsers.
WebDriver supports web as well mobile application testing so you can test mobile applications
(iPhone or Android).
Supporting latest versions of almost all browsers.
WebDriver controls the browser itself.
Selenium RC
Required selenium server for running test.
Selenium RC is using JavaScripts to drive automation with browser.
Selenium RC supports only web application testing.
Supporting all browsers but not supporting latest versions.
Selenium RC is using javascript to interact and operate on web page
You can share if you know any limitations or advantages of Selenium WebDriver by posting
comments bellow.
Click here (http://docs.seleniumhq.org/projects/webdriver/) to read more about WebDriver. You
can read my next post about
selenium webdriver download
install.
selenium web driver, selenium webdriver documentation, selenium testing, webdriver selenium,
selenium testing tool, selenium driver, selenium tool, automated testing tools, software testing tools,
selenium automation, selenium webdriver vs remote control, selenium online training, selenium
training, selenium test, selenium test tool, webdriver, automated testing tools, web testing tools, test
automation tools, selenium firefox webdriver.
3. How to download and install Selenium Webdriver with Eclipse and Java Step By
Step
Download selenium webdriver and install selenium webdriver is not much more hard. Actually
there is nothing to install except JDK. Let me describe you step by step process of download,
installation and configuration of web driver and other required components. You can view my post
about "
What is selenium webdriver
" if you wants to know difference between WebDriver and
selenium RC software tool.
(Note :
I am suggesting you to take a tour of Basic selenium commands tutorials with examples
before going ahead for webdriver. It will improve your basic knowledge and helps you to create
webdriver scripts very easily.
)
Steps To
Setup and configure Selenium Webdriver With Eclipse and Java
(Note : You can
View More Articles On WebDriverto learn it step by step)
Step 1 : Download and install Java in your system
First of all you need to install JDK (Java development kit) in your system. So your next question will
be "how can i download java"
Click here
to download Java and install it in your system as per given
installation guide over there.
Step 2 : Download and install Eclipse
Download
Eclipse for Java Developers and extract save it in any drive. It is totally free. You can run
'eclipse.exe' directly so you do not need to install Eclipse in your system.
Step 3 : Download WebDriver Java client driver.
Selenium webdriver supports many languages and each language has its own client driver. Here we
are configuring selenium 2 with java so we need 'webdriver Java client driver'.
Click here
to go on
WebDriver Java client driver download page for webdriver download file. On that page click on
'Download' link of java client driver as shown in bellow image.
(language-specific client driver's version is changing time to time so it may be different version when
you will visit download page. )
Downloaded 'webDriver Java client driver' will be in zip format. Extract and save it in your system at
path D:\selenium-2.33.0. There will be 'libs' folder, 2 jar files and change log in unzipped folder as
shown in bellow figure. We will use all these files for configuring webdriver in eclipse.
Step 4 : Start Eclipse and configure it with selenium 2 (webdriver)
Select WorkSpace on eclipse start up
Double click on 'eclipse.exe' to start eclipse. First time when you start eclipse, it will ask you to select
your workspace where your work will be stored as shown in bellow image. Create new folder in D:
drive with name 'Webdriverwork' and select it as your workspace. You can change it later on from
'Switch Workspace' under 'file' menu of eclipse.
After selecting workspace folder, Eclipse will be open.
Create new project
Create new java project from File > New > Project > Java Project and give your project name
'testproject' as shown in bellow given figures. Click on finish button.
Create new package
Right click on project name 'testproject' and select New > Package. Give your package name =
'mytestpack' and click on finish button. It will add new package with name 'mytestpack' under
project name 'testproject'.
Create New Class
Right click on package 'mytestpack' and select New > Class and set class name = 'mytestclass' and
Now your Eclipse window will looks like bellow.
Add external jar file to java build path
Now you need to add selenium webdriver's jar files in to java build path.
Right click on project 'testproject' > Select Properties > Select Java build path > Navigate to
Libraries tab
Click on add external JARs button > select both .jar files from D:\selenium-2.33.0.
Click on add external JARs button > select all .jar files from D:\selenium-2.33.0\libs
That's all about configuration of WebDriver with eclipse. Now you are ready to write your test in
eclipse and run it in WebDriver.
You can Read My Post about
how to write and run your first test in
WebDriver
.
download selenium webdriver, install webdriver, download webdriver selenium, selenium testing,
selenium testing tool, how to download selenium webdriver, what is selenium webdriver, webdriver
download, selenium webdriver download, selenium automation, selenium download, selenium install,
install selenium webdriver, install selenium webdriver in eclipse, eclipse and selenium, java and
selenium, how to install a server, selenium driver, how to setup selenium webdriver, download
webdriver selenium, selenium webdriver tutorial java.
4. Create And Run First Webdriver Script With Eclipse
Run First Webdriver Script
You need to
install webdriver with eclipse
to run your script in webdriver. After installation of
webdriver, You need to write a java code in eclipse for your test case of software web application. Let
me give you one simple example of creating simple webdriver script. First of all you need to write
code as bellow in your
'mytestclass.java' file. You can request(if you wish) this sample code file by submitting comment
bellow with your email id.
Now you are ready to run your script from Run menu as shown bellow.
Above script will open Firefox browser.
Then driver.get syntax will open 'http://only-testing-blog.blogspot.in/' in firefox browser.
Then driver.getCurrentUrl() will get the current page URL and it will be stored in variable
'i'. You can do same thing using
"storeLocation" command
in selenium IDE
And at last, it will print value of variable in console as shown bellow.
So this is the simple webdriver script example. You can create it for your own software web application
too by replacing URL in above script. We will learn more scripts in detail in my upcoming posts.
Running Selenium Webdriver Test In Google Chrome
You can read my THIS POST to know how to run selenium webdriver test of software application in Mozilla Firefox browser. As you know, webdriver support Google Chrome browser too. You need to do something extra for launching webdriver test in in Google chrome browser. Let me describe you steps to launch webdriver test in Google Chrome.
Download ChromeDriver server
First of all, download latest version of ChromeDriver server for webdriver. You can download it directly from http://code.google.com/p/chromedriver/downloads/list. Current latest
version for win32 is chromedriver_win32_2.3 as shown bellow.
Click on that link. It will take you to download page.
Click on link shown above to download chrome driver zip file. On completion of download, extract zip file to D:/ drive.
Now in eclipse, create new project with name = 'chromeproject' and create new class with name = 'chromebrowser'. Don't forget to select 'public static void main(String[] args)'
method during new java class creation. Write code as shown bellow in class file. You can request this copy of this code by submitting comment bellow this post.
Look in to above image. I set path for Google chrome driver as
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32_2.3\\chro
medriver.exe");
So now, your test will run in Google chrome browser.
5.
Different Ways Of Locating Elements In WebDriver
1) Selenium Webdriver Element Locator - Locating Element By Name With
Example
Selenium WebDriver/Selenium 2 is web and mobile application regression testing tool and it is using element locators to find out and perform actions on web elements. We have learn Element Locating by ID, Element Locating By Tag Name and Locating element by Class Name with examples in my previous
posts. Locating Element By Name is very useful method and many peoples are using this method in their webdriver automation test case preparation. Locating Element By Name and Locating Element by ID are nearly same. In Locating Element by ID method, webdriver will look for the specified ID attribute and in Locating Element By Name method, webdriver will look for the specified Name attribute.
Let me show you one example of how to locate element by name and then we will use it in our webdriver test case.
Look in to above image, web element 'First Name' input box do not have any ID so webdriver can not locate it By ID but that element contains name attribute. So webdriver can locate it By Name attribute. Syntax of locating element in webdriver is as bellow.
driver.findElement(By.name("fname"));
Now let we use it in one practical example as bellow.Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name"); }
Above example will type the text in text box using By Name element locating method.
2) Element Locators In Selenium 2 or WebDriver - Locating Element By Tag
Name
We have learn about Locating element by ID and Locating element by Class Name with examples in my previous posts. Let me repeat once more that if element contains ID then we can locate element by its ID and if element do not have ID and contains Class Name then we can locate an element by Class Name.
Now supposing, web element do not have any ID or Class Name then how to locate that element in selenium WebDriver ? Answer is there are many alternatives of selenium WebDriver element locators and one of them is Locating Element By Tag Name.
Locating Element By Tag Name is not too much popular because in most of cases, we will have other alternatives of element locators. But yes if there is not any alternative then you can use element's DOM Tag Name to locate that element in webdriver.
(Note : You can view all tutorials of webdriver element locators)
Look in to above image. That select box drop down do not have any ID or Class Name. Now if we wants to locate that element then we can use it's DOM tag name 'select' to locate that element. Element locator sysntex will be as bellow.
driver.findElement(By.tagName("select"));
Bellow given example will locate dropdown element by it's tagName to store its values in variable. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.(Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
System.out.print("Drop down list values are as bellow :\n"+dropdown); }
3) How To Locate Element By XPATH In Selenium 2/WebDriver With Example
We have learnt most of all the way of locating element in webdriver like Locating Element By ID, Locating Element By Name, Locating Element By Class Name,Locating Element By Tag Name, Locating Element By Link Text Or Partial Link
and Locating Element By CSS Selector. One
another method of locating element in selenium webdriver is By XPATH of element. It is most popular and best way to locate element in WebDriver. However you can use other ways too to locate element.
You can write Xpath of any element by many different ways as described in This Post.
Above given image shows the firebug view of First name text box. Now let me give you few examples of how to write syntax to locate it in webdriver using xPath in 2 different ways.
1. driver.findElement(By.xpath("//input[@name='fname']"));
2. driver.findElement(By.xpath("//input[contains(@name,'fname')]"));
I have used xPath to locate element in above both the syntax. We can use anyone from above to locate that specific element. Let we use it in practical example as bellow.
Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");//Locate element by cssSelector and then type the text in it.
4) Selenium WebDriver By.cssSelector Element Locators With Example
WebDriver support many different element locating methods and locating element by it's CSS Path is one of the most popular way in webdriver. If you not want to use by id, name, tag name, class name or link text as your locator then you can locate that element by it's CSS path. Read this tutorial to learn different ways of writing CSS path of any element. You can get CSS path of any element using selenium IDE too by setting CSS as your Locator Builders Preference and then performing some action on that element in Selenium IDE recording mode. You can get CSS path of any element by Firebug too.
Now let we learn how we can use By.cssSelector in webdriver. Look in to bellow given image.
Here we can locate input box First name using bellow given webdriver syntax. driver.findElement(By.cssSelector("input[name='fname']"));
Bellow given example will locate input box by CSS Selector to type text in it.
Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("My Name");;//Locate element by cssSelector and then type the text in it.
}
5) How To Locate Element By Link Text Or Partial Link Text In Selenium
WebDriver
In my previous posts what we have learn is we can Locate Element By Name, Locate Element By ID, Locate Element By Class Name And Locate Element By Tag Name to take any action on that element. We will look about different web driver actions and operations in my upcoming posts. Now let we learn two more element locators as bellow.
Locate Element By Link Text
If your targeted element is link text then you can use by link text element locator to locate that element. Look in to bellow given image.
My Targeted element Is Link text 'Click Here' and I wants to click on It then I can use It as bellow.
driver.findElement(By.linkText("Click Here")).click();
Locate Element By Partial Link Text
Same as Link text, We can locate element by partial link text too. In that case we need to use By.partialLinkText at place of By.linkText as bellow.
driver.findElement(By.partialLinkText("Click ")).click();
For locating element by link text, we need to use full word 'Click Here' but in case of locating element by partial link text, we can locate element by partial work 'Click' too. Look in to bellow given example. I have used both the element locators to locate links. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.linkText("Click Here")).click();//Locate element by linkText and then click on it.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("18:"))); / /Locate element by partial linkText.
6) Locating Web Element By ClassName In Selenium WebDriver with example
There are many different ways of locating elements in webdriver for your software web application page and I have described one of them in my PREVIOUS POST with example. In webdriver, we can't do any thing on web page if you don't know how to locate an element. As you know, we can use element's ID to locate that specific element but suppose if your element do not have any ID then how will you locate that element ? Locating web element by className is good alternative if your element contains class name. We can locate element By Tag Name, By Name, By Link Text, By Partial Link Text, By CSS and By XPATH too but will look about them in my next posts.How to get the class name of element
You can get the class name of element using firebug as shown in bellow given image.
Look in to above image. Post date content has a class and we can use that class name to store that blog post date string. Notice one more thing in above image, blog post date string has not any ID so we can not locate it by ID.
(Note : You can view more webdriver tutorials on THIS LINK.)
Example Of Locating Web Element By ClassName
We can use bellow given syntax to locate that element.
driver.findElement(By.className("date-header"));
Practical example of locating web element by className is as bellow.
package junitreportpackage; 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 Mytest1 {
//To open Firefox browser
WebDriver driver = new FirefoxDriver(); @Before
//To Maximize Browser Window
driver.manage().window().maximize();
//To Open URL In browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); }
@After
public void aftertest() { driver.quit();
}
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); String datentime =
driver.findElement(By.className("date-header")).getText();//Locating element by className and store its text to variable datentime.
System.out.print(datentime); }
}
7) How To Locate Elements By ID In Selenium WebDriver With Example
Before using WebDriver, You must be aware about different ways of locating an elements in WebDriver. Locating an element is essential part in selenium WebDriver because when you wants to take some action on element (typing text or clicking on button), first you need to locate that specific element to perform action.
First of all I recommend you to read all these selenium IDE element locating methods and then read this article about Selenium WebDriver element locators to get all locating methods in better way.
WebDriver which is also known as a Selenium 2 has many different ways of locating element. Let me explain each of them with examples. Here I am explaining how to locate element By id and will describe Locating Web Element By ClassName in my Next Post and others in latter posts.
Locating UI Element By ID
If your webpage element has unique and static ID then you can locate your page element by ID. Look in to bellow given image. You can verify that your webelement has any id or not using the firebug.
In above image, Submit Query button has unique id = 'submitButton'. I can use that id to locate button as bellow.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then how to click on it. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.(Note : @Test method is marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating element by id
if (btn.isEnabled()) {
//if webelement's attribute found enabled then this code will be executed. System.out.print("\nCongr8s... Button is enabled and webdriver is clicking on it now");
//Locating button by id and then clicking on it.
driver.findElement(By.id("submitButton")).click(); i=20; } else {
//if webelement's attribute found disabled then this code will be executed. System.out.print("\nSorry but Button is disabled right now..");
} try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }
6. Selenium WebDriver Tutorials - Basic Action Commands And Operations With
Examples
I have already posted Selenium WebDrier Tutorials posts how to
setup web driver with
eclipse and
Run first test with webdriver
, how to
configure junit with eclipse to generate
webdriver test report
. We have also learn different methods of
locating elements in webdriver
. All
these things are very basic things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing basic actions in web driver
with java for your software web application.
VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER
Today I wants to describe you few basic webdriver commands to perform actions on web element of
your web page. We can perform too many command operations in webdriver and will look about
them one by one in near future. Right now I am describing you few of them for your kind
information.
1. Creating New Instance Of Firefox Driver
WebDriver driver = new FirefoxDriver();Above given syntax will create new instance of Firefox driver.
VIEW PRACTICAL EXAMPLE
2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser.
VIEW PRACTICAL EXAMPLE OF OPEN
URL
3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver.
VIEW PRACTICAL EXAMPLE
OF CLICK ON ELEMENT
4. Store text of targeted element in variable
String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element and will store it in variable = dropdown.
VIEW
PRACTICAL EXAMPLE OF Get Text
5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element.
VIEW PRACTICAL EXAMPLE OF
SendKeys
6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found on page.
VIEW PRACTICAL EXAMPLE OF IMPLICIT WAIT7. Applying Explicit wait in webdriver with WebDriver canned conditions.
WebDriverWait wait = new WebDriverWait(driver, 15);wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id ='timeLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be appear on
targeted element.
VIWE DIFFERENT PRACTICAL EXAMPLES OF EXPLICIT WAIT8. Get page title in selenium webdriver
driver.getTitle();It will retrieve page title and you can store it in variable to use in next steps. VIEW PRACTICAL EXAMPLE
OF GET TITLE9. Get Current Page URL In Selenium WebDriver
driver.getCurrentUrl();It will retrieve current page URL and you can use it to compare with your expected URL.
VIEW PRACTICAL EXAMPLE OF GET CURRENT URL10. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain");
Above syntax will retrieve your software application's domain name using webdriver's java script
executor interface and store it in to variable.
VIEW GET DOMAIN NAME PRACTICAL EXAMPLE .11. Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;javascript.executeScript("alert('Test Case Execution Is started Now..');");
It will generate alert during your selenium webdriver test case execution.
VIEW PRACTICAL EXAMPLE OFGENERATE ALERT USING SELENIUM WEBDRIVER
.
12. Selecting or Deselecting value from drop down in selenium webdriver.
Select By Visible Text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist"))); mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".
Select By Value
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.selectByValue("Italy");
It will select value by value = "Italy".
Select By Index
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.selectByIndex(0);
It will select value by index= 0(First option).
VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM DROP DOWN LIST
.
Deselect by Visible Text
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.
Deselect by Value
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.
Deselect by Index
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.
Deselect All
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectAll();
It will remove all selections from list box.
VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION FROM LIST BOX
isMultiple()
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.
VIEW PRACTICAL EXAMPLE OFisMultiple()
13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html"); driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step back and 3rd command will
navigate one step forward.
VIEW PRACTICAL EXAMPLES OF NAVIGATION COMMANDS .14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent =driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in variable iselementpresent.
VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT PRESENT.
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive.
VIEW PRACTICAL EXAMPLE ON THIS PAGE.
Actions actions = new Actions(driver);
WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div")); actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element.
VIEW PRACTICAL EXAMPLE OF MOUSE HOVER.
17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();
2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0]; String window2 = (String) AllWindowHandles.toArray()[1];
3. Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to switch from one window to
another window.
VIEW PRACTICAL EXAMPLE OF HANDLING MULTIPLE WINDOWS IN WEBDRIVER18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.
boolean fname =driver.findElement(By.xpath("//input[@name='fname']")).isEnabled(); System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input
element. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT IS ENABLED OR NOT.
19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;String todisable = "document.getElementsByName('fname') [0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname') [0].removeAttribute('disabled');";
javascript.executeScript(toenable);
It will disable fname element using setAttribute() method and enable lname element
using removeAttribute() method.
VIEW PRACTICAL EXAMPLE OF ENABLE/DISABLE TEXTBOX.
20. Selenium WebDriver Assertions With TestNG Framework
assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal values. VIEW PRACTICAL EXAMPLE OF
assertEquals ASSERTION
assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values.
VIEW PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.
assertTrue
assertTrue assertion works for boolean value true assertion.
VIEW PRACTICAL EXAMPLE OF assertTrue ASSERTION.
assertFalse
Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. VIEW PRACTICAL EXAMPLE OF assertFalse
ASSERTION.21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.
22. Handling Alert, Confirmation and Prompts Popups
String myalert = driver.switchTo().alert().getText();
To store alert text.
VIEW PRACTICAL EXAMPLE OF STORE ALERT TEXTdriver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT
driver.switchTo().alert().dismiss();
To dismiss confirmation.
VIEW PRACTICAL EXAMPLE OF CANCEL CONFIRMATIONdriver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup.
VIEW PRACTICAL EXAMPLE OF TYPE TEXT IN PROMPT TEXT BOX7. Web Driver Featutes
How to use implicit & explicit wait in selenium webdriver and why
There are 2 types of waits available in Webdriver/Selenium 2. One of them is implicit wait and another one is explicit wait. Both (Implicit wait and explicit wait) are useful for waiting in WebDriver. Using waits, we are telling WebDriver to wait for a certain amount of time before going to next step. We will see about explicit
wait in my upcoming posts. In this post let me tell you why and how to use implicit wait in webdriver.
Why Need Implicit Wait In WebDriver
As you knows sometimes, some elements takes some time to appear on page when browser is loading the page. In this case, sometime your webdriver test will fail if you have not applied Implicit wait in your test case. If implicit wait is applied in your test case then webdriver will wait for specified amount of time if targeted element not appears on page. As you know, we can Set default timeout or use "setTimeout" command in selenium IDE which is same as implicit wait in webdriver.
If you write implicit wait statement in you webdriver script then it will be applied automatically to all elements of your test case. I am suggesting you to use Implicit wait in your all test script of software web application with 10 to 15 seconds. In webdriver, Implicit wait statement is as bellow.
Above statement will tell webdriver to wait for 15 seconds if targeted element not found/not appears on page. Le we look at simple exemple to understand implicit wait better.
Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example).
@Test
public void test () {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name"); driver.findElement(By.xpath("//input[@name='namexyz']"));
}
In Above webdriver test case with JUnit example, 1st Element 'xpath("//input[@name='fname']")' will be found on page but element xpath("//input[@name='namexyz']") is not there on page. So in this case webdriver will wait for 15 to locate that element on page because we have written implicit wait statement in our code. At last webdriver test will fail because xpath("//input[@name='namexyz']") is not on the page.
Implicit wait will be applied to all elements of test case by default
while explicit will be applied to targeted element only. This is the difference between implicit wait and explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitButton" )));
wait for text to be present with example using explicit wait
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id ='timeLeft']"), "Time left: 7 seconds"));
wait for alert in selenium 2
WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.alertIsPresent());
How to wait till element visible or appear or present on page
In any software web application's webdriver test case, you can easily wait for presence of element
using
IMPLICIT WAIT
. If you have used implicit wait in your test case then you do not require to
write any extra conditional statement to wait for element visibility. But in some cases, if any element is taking too muchtime
to be visible on page then you can use
EXPLICIT WAIT
condition in your test case.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='t ext3']")));
Here above syntax will wait till 15 seconds to become targeted element(#submitButton) clickable if it is not clickable or not loaded on the page of software web application. As soon as targeted element becomes clickable, webdriver will go for perform next action.
Difference Between findElement and findElements with example
We have seen many examples of webdriver's findElement() in my previous posts. You will find
syntax of findElement() with example on
THIS PAGE
if you wants to use it in your software web
application test case. Selenium WebDriver has one more related command findElements. Now main
question
is
what
is
the
difference between findElement and findElements methods in selenium 2? First of all let me provide
you difference description and then example.
findElement() method
We need to use findElement method frequently in our webdriver test case because this is the
only way to locate any element in webdriver.
findElement method is useful to locating targeted single element.
If targeted element is not found on the page then it will throw NoSuchElementException.
findElements() method
We are using findElements method just occasionally.
findElements method will return list of all the matching elements from current page as per
given element locator mechanism.
If not found any element on current page as per given element locator mechanism, it will
return empty list.
Now let me provide you simple practical example of findElement method and findElements method
to show you clear difference. You can
VIEW ALL PRACTICAL EXAMPLES OF SELENIUM
WEBDRIVER
one by one.
Copy bellow given @Test method part of findElement and findElements method examples and
replace it with the @Test method part of example given on
THIS PAGE. (Note : @Test method is
marked with
pink color in
that linked page).
@Test
public void test () throws InterruptedException {
WebElement option = driver.findElement(By.xpath("//option[@id='country5']")); System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option")); System.out.println(options.size());
for(int i=0;i<=options.size();i++) {
String str = options.get(i).getAttribute("id")+" - "+options.get(i).getText(); System.out.println(str);
} }
In above example, findElement will locate only targeted element and then print its id and text in console
while findElements will locate all those elements of current page which are under given xpath = //option.
for loop is used to print all those element's id and text in console.
Same way you can locate all input elements, link elements etc.. using findElements method.
How To Generate And Insert Log In Selenium Webdriver Using log4j Jar
Assume you have prepared test case for your software web application test scenario (using selenium
webdriver with eclipse and junit) and now you wants generate log file to insert your execution time log
messages in to it. How you will do it? Selenium webdriver do not have any built in function or method to
generate log file. In this case you can use apache logging service. Let me describe you steps to generate
log
file
in
selenium
webdriver.
Steps To Generate And Insert Log In Selenium Webdriver
1. Download log4j jar file from logging.apache.org
Click Here
to go to log4j jar file downloading page. (This Link URL may change in future).
Click on Zip folder link as shown in bellow image. Current version of log4j jar file is
log4j-1.2.17. Version of log4j jar file may be different in future due to the frequent version change.
When you click on zip folder link, it will show you zip mirror links to download folder.
Download and save zip folder by clicking on mirror link.
Now Extract that zip folder and look inside that extracted folder. You will find log4j-1.2.17.jar file
in it.
2. Import log4j-1.2.17.jar file in your eclipse project from
Right click on your project folder and go to Build Path -> Configure Build path. It will open java
build path window as shown in bellow image.
Click on Add External JARs button and select log4j-1.2.17.jar file. It will add log4j-1.2.17.jar file
in your build path.
Click on OK button to close java build path window.
3. Create Properties folder under your project folder and add log4j.properties file in it.
Create folder with name = Properties under your project by right clicking on your project folder.
Click Here
to download log4j.properties file and save it in Properties folder which is created
under your project folder.
Now your properties folder under project folder will looks like bellow.
4. Set Run Configuration
This is optional step. You need to set your Run configure if log file is not generated and display bellow
given warning message in your console when you run your test case.
log4j:WARN No appenders could be found for logger (dao.hsqlmanager).
Go to Run -> Run Configurations -> Classpath
Select User Entries -> Click on 'Advanced' button -> Select Add Folder -> And then select
Properties folder from your project and click on OK. Now your Class tab will looks like bellow.
5. Create example(Sample) test case under your project.
Create your own test case or copy example test case
from here
and paste it in your class file.
6. Import log4j header file in your project
Import bellow given header file in your test case class file.
import org.apache.log4j.*;
@Test
public void test () throws InterruptedException {
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name"); log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist"))); mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class); log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2"))); }
When your test case is executed, Go to folder = C:\Logs. log.log file will be created over there. Open that
file and look in to it. Log written in your test case will be inserted in your log file. In above example,
Syntax marked with
Pink color
are written for inserting log. Now you can write log at any place in your
test case as shown in above example.
Creating Object Repository Using Properties File In Selenium WebDriver
In selenium WebDriver, There Is not any built In facility to create object repository. So maintenance of page objects(Page element locators) becomes very hard If you will write all objects of page on code level. Let me give you one simple example - You have one search button and you have used It(Using Id locator) In many
of your test cases. Now supposing someone has changed Its Id In your application then what you will do? You will go for replacing Id of that element In all test cases wherever It Is used? It will create overhead for you. Simple solution to remove this overhead Is creating object repository using properties File support of java. In properties file, First we can write element locator of web element and then we can use It In our test cases.
Let us try to create object repository for simple calculator application given on THIS PAGE
and then will try to create test case for that calc application using object repository..
How to create new properties file
It will open New wizard. Expand General folder In New wizard and select File and click on Next button.
It will add object.properties file under your package. Now copy paste bellow given lines in objects.properties file. So now this objects.properties file Is object repository for your web application page calc.
objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1 two=2 three=3 four=4 five=5 six=6 seven=7 eight=8 nine=9 zero=0 equalsto=equals cler=AC result=Resultbox plus=plus minus=minus mul=multiply
In above file, Left side value Is key and right side value Is element locator(by Id) of all web elements of web calculator. You can use other element locator methods too like xpath, css ect.. VISIT THIS LINK to view different element locator methods of webdriver.
Now let us create webdriver test case to perform some operations on calculation. In bellow given example, All the element locators are coming from objects.properties file using obj.getProperty(key). Here key Is reference of element locator value in objects.properties file.
package ObjectRepo; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
public class CalcTest {
WebDriver driver = new FirefoxDriver(); @BeforeMethod
public void openbrowser() throws IOException { driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html"); }
@AfterMethod
public void closebrowser() { driver.quit();
} @Test
public void Calc_Operations() throws IOException{ //Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir") +"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
//Sum operation on calculator.
//Accessing element locators of all web elements using obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("eight"))).click(); driver.findElement(By.id(obj.getProperty("plus"))).click(); driver.findElement(By.id(obj.getProperty("four"))).click(); driver.findElement(By.id(obj.getProperty("equalsto"))).click(); String i = driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value"); System.out.println(obj.getProperty("eight")+" + "+obj.getProperty("four")+" = "+i); driver.findElement(By.id(obj.getProperty("result"))).clear();
//Subtraction operation on calculator.
//Accessing element locators of all web elements using obj.getProperty(key) driver.findElement(By.id(obj.getProperty("nine"))).click(); driver.findElement(By.id(obj.getProperty("minus"))).click(); driver.findElement(By.id(obj.getProperty("three"))).click(); driver.findElement(By.id(obj.getProperty("equalsto"))).click(); String j = driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")+" = "+j);
} }
Run above given example In your eclipse and observe execution.
Now supposing I have many such test cases and some one has changed Id of any button of calc application then what I have to do? I have to modify all test cases? Answer Is No. I just need to modify objects.properties file because I have not use element's Id directly In any test case but I have Used just Its key reference In all test cases.
This way you can create object repository of all your web elements In one .properties file. You can VIEW MORE TUTORIALS about selenium webdriver.
How To Get/Extract All Links From Web Page Using Selenium WebDriver
As we all knows, Each and every software web application contains many number of different links/URLs. Some of them are redirecting to some page of same website and others are redirecting to any external website. One of my blog reader has requested the webdriver test script example for printing all these links in
console. I have created and published many different WEBDRIVER EXAMPLE SCRIPTS on this blog but requested example by blog reader is not pushed till now so I have created example for the same to share with all of you.
You can look at example of EXTRACTING TABLE DATA USING SELENIUM WEBDRIVER.
We have seen HOW TO USE findElements in webdriver to locate multiple elements of page. We can use same thing here to locate multiple links of the page. Bellow given example will retrieve all URLs from the page and will print all of them in console. You can click on each URL if you wish to do so. Try bellow given example for different websites by providing that website's URL in @Before annotation.
Copy bellow given @Test method part of extract all links from web page and replace it with the @Test method part of example given on THIS PAGE.(Note : @Test method is marked
with pink color in that linked page).
@Test
public void test () throws InterruptedException {
try {
List<WebElement> no = driver.findElements(By.tagName("a")); int nooflinks = no.size();
System.out.println(nooflinks); for (WebElement pagelink : no) {
String linktext = pagelink.getText();
System.out.println(linktext+" ->"); System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e); }
}
How To Extract Table Data/Read Table Data Using Selenium WebDriver Example
Table Is very frequently used element In web pages. Many times you need to extract your web table data to compare and verify as per your test case. You can read about How To Extracting All Links From Page If you need It In your test scenarios. If you knows, Selenium IDE has also many commands related to Table
and you can view all of them on LINK 1 and LINK 2 with examples. Now let me come to our current discussion point about how to read values from table. Before reading values from web table, You must know there are how many rows and how many columns In your table. Let we try to get number of rows and columns from table.
SELENIUM WEBDRIVER STEP BY STEP TUTORIALS
.How To Get Number Of Rows Using Selenium WebDriver
Look at the firebug view of above HTML table. In any web table, Number of <tr> tags Inside <tbody> tag describes the number of rows of table. So you need to calculate that there are how many <tr> tags Inside <tbody> tag. To get row count for above given example table, we can use webdriver statement like bellow.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr")).size();
In above syntax, .size() method with webdriver's findElements method will retrieve the count of <tr> tags and store It In Row_count variable.
How To Get Number Of Columns Using Selenium WebDriver
Same way In any web table, Number of <td> tags from any <tr> tag describes the number of columns of table as shown In bellow given Image.
So for getting number of columns, we can use syntax like bellow.
int Col_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
Now we have row count and column count. One more thing you require to read data from table Is generating Xpath for each cell of column. Look at bellow given xpath syntax of 1st cell's 1st and 2nd rows.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1] //*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]
Highlighted string Is common for both cell's xpath. Only changing Is row number Inside tr node. So here we can pass Row_count variable's value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st row. Highlighted string Is common for both cell's xpath. Only changing Is column number Inside td node. So here we can pass Col_count variable's value Inside td node.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1] //*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]
All above thing Is applied In bellow given example. Simply run It In your eclipse using testng and observe output In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit; import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
public class table {
WebDriver driver = new FirefoxDriver(); @BeforeTest
public void setup() throws Exception { driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/09/test.html"); }
@AfterTest
public void tearDown() throws Exception { driver.quit();
} @Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);
//Get number of columns In table.
int Col_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
System.out.println("Number Of Columns = "+Col_count);
//divided xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr["; String second_part = "]/td[";
String third_part = "]";
//Used for loop for number of rows.
for (int i=1; i<=Row_count; i++){
//Used for loop for number of columns.
for(int j=1; j<=Col_count; j++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part; //Will retrieve value from located cell and print It.
String Table_data = driver.findElement(By.xpath(final_xpath)).getText(); System.out.print(Table_data +" "); } System.out.println(""); System.out.println(""); } } }
Number Of Rows = 3 Number Of Columns = 6 11 12 13 14 15 16 21 22 23 24 25 26 31 32 33 34 35 36
Here you can see, all the values of table are extracted and printed.
How To Handle Dynamic Web Table In Selenium WebDriver
If web table has same number of rows and same number of cells In each rows every time you load page then It Is very easy to handle that table's data In selenium WebDriver as described In How To Extract Table Data/Read Table Data Using Selenium WebDriver
post. Now supposing your table's rows and
columns are increasing/decreasing every time you loading page or some rows has more cells and some rows has less cells then you need to put some extra code In your webdriver test case which can retrieve cell data based on number of cells In specific row. Consider the table shown In bellow given Image.
In this table, Row number 1, 2 and 4 has 3 cells, Row number 3 has 2 Cells and Row 5 has 1 cell. In this case, You need to do some extra code to handle these dynamic cells of different rows. To do It, You need to find out the number of cells of that specific row before retrieving data from It.
You can view more webdriver tutorials with testng and java WEBDRIVER TUTORIAL @PART 1 and WEBDRIVER TUTORIAL @PART 2.
Bellow given example will first locate the row and then It will calculate the cells from that row and then based on number of cells, It will retrieve cell data Information.
Run bellow given example In your eclipse with testng which Is designed for above given dynamic web table.
package Testng_Pack; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
public class dynamic_table {
WebDriver driver = new FirefoxDriver(); @BeforeTest
public void setup() throws Exception { driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html"); }
@AfterTest
public void tearDown() throws Exception { driver.quit();
} @Test
public void Handle_Dynamic_Webtable() { //To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body-8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr")); //To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.
List<WebElement> Columns_row =
rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){ //To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext); } System.out.println("---"); } } }
Above example will works for dynamic changing web table too where number of rows changing every time you load the page or search for something.
What Is the Firefox Profile?
When you Install Firefox In your computer, Firefox creates one default profile folder In your local drive
to save your preferences like your bookmarks, your preferred home page on Firefox open, your toolbar
settings, your saved passwords and all the other settings. You can create different profiles for your
Firefox
browser as per your requirement. Now supposing same computer Is used by two users and both wants
their own Firefox settings then both users can create their own Firefox profile to access their own settings
when he/she opens Firefox browser.
You can
LEARN SELENIUM WEBDRIVER STEP BY STEP
to become master of selenium
Webdriver.
If you have noticed, When you will run your selenium webdriver test In Firefox browser then WebDriver
will open blank Firefox browser like No bookmarks, No saved passwords, No addons etc.. as shown In
bellow given Image.
If you wants access of all these things In your selenium webdriver test browser then you have to create
new profile of Firefox and set all required properties In newly created profile and then you can access
that profile In webdriver using FirefoxProfile class of webdriver.
First Of all, Let us see how to create new profile of Firefox and then we will see how to use that profile
In your test.
How to Create New Custom Firefox Profile For Selenium WebDriver?
To create new firefox profile manually,
Close Firefox browser from File -> Exit.
Go to Start -> Run and type "firefox.exe -p" In run window and click OK. It will open "Firefox -
Choose User Profile" dialogue as shown In bellow Image.
Now click on Create profile button. It will open create profile wizard dialogue. Click On Next as
shown In bellow given Image.
On next screen, Give profile name = "WebDriver_Profile" and click on finish button as shown In
bellow given Image.
It Will create new profile of Firefox.
To use that newly Created profile, Select that profile and click on Start Firefox button as shown In
bellow given Image. It will open Firefox browser with newly created profile.
Now you can make you required settings on this new created profile browser like add your
required addons, bookmark your required page, network settings, proxy settings, etc.. and all other
required settings.
How To Access Custom Firefox(Changing User Agent) Profile In Selenium WebDriver Test
To access newly created Firefox profile In selenium WebDriver, We needs to use webdriver's Inbuilt
class ProfilesIni and Its method getProfile as shown In bellow given example.
package Testng_Pack; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
public class custom_profile { WebDriver driver;
@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its method getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile = firProfiles.getProfile("WebDriver_Profile"); //Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile); }
@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html"); }
@AfterTest
public void CloseBrowser() { driver.quit();
} }