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 of software web application 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.





Today I wants to describe you few basic webdriver commands to perform actions on web element of your software web application's web page. We can perform too many command operations in webdriver to automate software application test process and will look about them one by one in near future. Right now I am describing you few of them for your kind information. Bellow given commands are commonly used commands of selenium webdriver to use in automation process of any software web application.

1. Creating New Instance Of Firefox Driver
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
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.com/2013/11/new-test.html");
This syntax will open specified URL of software web application 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 of software web application page 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 of software web application. VIEW PRACTICAL EXAMPLE OF IMPLICIT WAIT

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

8. 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 TITLE

9. 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 URL

10. 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 OF GENERATE 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 of software application's page.

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 OF isMultiple()


13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-blog.blogspot.com/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.

16. Generating Mouse Hover Event In WebDriver
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.
  2. Set<String> AllWindowHandles = driver.getWindowHandles();
  3. Extract parent and child window handle from all window handles.
  4. String window1 = (String) AllWindowHandles.toArray()[0];
    String window2 = (String) AllWindowHandles.toArray()[1];
  5. Use window handle to switch from one window to other window.
  6. 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 WEBDRIVER

18. 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
Assert.assertTrue(condition);
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 TEXT

driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT

driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL CONFIRMATION

driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup. VIEW PRACTICAL EXAMPLE OF TYPE TEXT IN PROMPT TEXT BOX

46 comments:

  1. What is diffrence between findeElement() and findElements()?

    ReplyDelete
    Replies
    1. findeElement() is useful to locate single element (text box, link etc..) from page while findElements() is useful to locate multiple elements (All input fields from page, All links from page, etc..) from the page.

      findeElement() Example -> http://software-testing-tutorials-automation.blogspot.in/2014/01/how-to-locate-elements-by-id-in.html

      findElements() Example ->http://software-testing-tutorials-automation.blogspot.in/2014/02/how-to-getextract-all-links-from-web.html

      Delete
    2. findeElement() :Return one single WebElement With in the Currentpage.

      findElements():Return List of WebElement With in the Currentpage.

      Delete
    3. findElement(); return the first Web element of the list of the Web Elements within a current page
      findElements() ; return the list of Web Elemnents within a current page

      Delete
    4. findElement() ; Return first and single element of the element list in the current page
      findElements() ; Return the list of the Web Elements in the current page

      Delete
    5. findElement() ; Return first and single element of the element list in the current page
      findElements() ; Return the list of the Web Elements in the current page

      Delete
  2. Thanks a lot for sharing such a useful information...keep up the good work...:)

    ReplyDelete
  3. Thanks a lot for sharing such a vital info

    ReplyDelete
  4. Superb thank you

    ReplyDelete
  5. Awesome ... Very Helpful for anyone to get started...

    ReplyDelete
  6. awesome post thanks to sharing.

    ReplyDelete
  7. Any body tell me how to Run Selenium tests in parallel on multiple browsers .

    ReplyDelete
  8. Awesome tutorial thanks for sharing, if you could please add about check boxes and checking random checkbox's.

    ReplyDelete
  9. Any body tell me how to select random check boxes in selenium webdriver

    ReplyDelete
  10. good content

    ReplyDelete
  11. the web page has list of products ,in that i have to select any of one product that mus be within the range of 1000-1500,after selecting it,after selected checked out whether the product i s within range or not how to tets it plz can anyone tell this scenario

    ReplyDelete
    Replies
    1. Need to look In that page and then we can decide how to do It? Send me your site link.

      Delete
  12. This blog is beyond the expectations.. Excellent and thank you very much...

    ReplyDelete
  13. Wonderful Tutorials...Thanks for Sharing

    ReplyDelete
  14. Worth full info for Beginners. Thanks a lot.

    ReplyDelete
  15. Example 10
    JavascriptExecutor javascript = (JavascriptExecutor) driver;

    After casting the 'driver' object into JavascriptExecutor ,i'm not able to get the executeScript() method in the intellisense

    where am i wrong?

    ReplyDelete
  16. Can you tell me how to use random string generator in selenium Web Driver using JAVA ?
    It will helpful if you provide an example.
    Thanx.

    ReplyDelete
  17. Thank you .It helps a lot keep updating..

    ReplyDelete
  18. Very detailed and nice tutorial.I am on the way of learning data driven framework I hope this tutorial will going to help me a lot.Thanks for such tutorial

    ReplyDelete
  19. excellent tutorial for those who are initiating thanks

    ReplyDelete
  20. This is really helpful for the beginners. Keep the good work going... :) Thanks

    ReplyDelete
  21. good work..very much helpful

    ReplyDelete
  22. very useful info.. keep it posting.

    ReplyDelete
  23. very useful info.

    ReplyDelete
  24. Very useful Info for Selenium beginners.

    ReplyDelete
  25. How can I start web browser in background ?

    ReplyDelete
  26. Hi,
    I cannot use sendKeys() command with search-view control in Odoo framework. It does't work.
    Help me please!
    Thanks so much

    ReplyDelete
  27. Hi,
    I cannot use sendKeys() command with search-view control in Odoo framework. It doesn't work.
    Help me please!
    Thanks so much

    ReplyDelete
  28. Arun Masta (arunmasta@gmail.com)
    Amazing, thanks a lot my friend, I was also siting like a your banner image when I was thrown into Selenium.
    When I started learning then I understood it has got really cool stuff.
    I can vouch webdriver has proved the best feature in Selenium framework.
    thanks a lot for taking a time to share a wonderful article.

    ReplyDelete
  29. Thanks for sharing this with us. Helpful

    ReplyDelete
  30. I am using the driver.getCurrentUrl();
    but current url is not displaying in my console.
    What is the issue?

    ReplyDelete
  31. Awesome, covered everything, you nailed it man.

    ReplyDelete
  32. Very Useful info, Hats off to you. Additional to that

    //To Navigate next tab in the same browser
    ArrayList newTab = new ArrayList (driver.getWindowHandles());
    driver.switchTo().window(newTab.get(1));

    ReplyDelete
  33. Made easy for beginners to learn and understand from the basics. Thank you so much for helping us.

    ReplyDelete
  34. Very interesting, good job and thanks for sharing such a good blog. I am looking for some good Live project training for get project experience.

    ReplyDelete
  35. Please Make a tutorial for these commands on chrome.

    Finding base profiles
    Creating profiles with custom options
    Updating profiles with new settings
    How to start a profile
    Using WebDriver with Local API
    Adding an HTTP, SOCKS or SSH proxy to profile
    Saving/Loading a browsing session to/from a .chrome profile file
    Modify and Delete browser cookies
    Hooking up Chrome with an external browser (Puppeteer)

    ReplyDelete