15+ Useful Selenium Web driver Code Snippets



Main reason for extreme popularity and success of Web Driver is its ability to easily simulate
the action of a real website user.

This library can control the browser and supports wide variety of browsers including all popular ones like Firefox, Chrome, Safari and IE.

The programming for web driver scripts can be done in Java, Python, Ruby and .NET. This article focuses on only Java code snippets, however the equivalent code can be easily written in any other supported language.

Some of the very common use cases like taking an error snapshot, or uploading a file are very easily accomplished using Web Driver API. 

Below are some of the code snippets that are frequently used when creating java test cases using Selenium web driver. I hope this will help you save some time in your test case code creation.


Instantiate Specific Browser or Client


Firefox Driver
          WebDriver driver = new FirefoxDriver();

        Chrome Driver

           WebDriver driver = new ChromeDriver();

     Safari Driver

          WebDriver driver = new SafariDriver();

      Internet Explorer Driver
    WebDriver driver = new InternetExplorerDriver();

Android Driver

           WebDriver driver = new AndroidDriver()

        iPhone Driver

                WebDriver driver = new IPhoneDriver();

.    HTML Unit

                WebDriver driver = new HtmlUnitDriver()

Check If an Element Exists

You may need to perform an action based on a specific web element being present on the web page. You can use below code snippet to check if a element with id “element-id” exists on web page. 

              driver.findElements(By.id("element-id")).size()!=0

 

How to Check If an Element Is Visible With WebDriver

The above mentioned method may be good to check if a element exists on page. However sometimes an element may be not visible, therefore you cannot perform any action on it. You can check whether an element is visible or not using below code.

              WebElement element  = driver.findElement(By.id("element-id"));
            if(element instanceof RenderedWebElement) {
            System.out.println("Element visible");
             } else {
           System.out.println("Element Not visible");
            }

Refresh Page

This may be required often. Just a simple refresh of the page equivalent to a browser refresh.

                  driver.navigate().refresh();

Navigate Back and Forward On the Browser
Navigating the history of browser can be easily done using below two methods. The names are self explanatory. 
            //Go back to the last visited page
              driver.navigate().back();
        
              //go forward to the next page
               driver.navigate().forward();

  Wait For Element to Be Available
The application may load some elements late and your script needs to stop for the element to be available for next action. You can perform this check using below code.
In below code, the script is going to wait maximum 30 seconds for the element to be available. Feel free to change the maximum number per your application needs.

                WebDriverWait wait = new WebDriverWait(driver, 30);
                WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("id123")));
  

Focus On an Input Element on Page

Doing focus on any element can be easily done by clicking the mouse on the required element. However when you are using selenium you may need to use this workaround instead of mouse click you can send some empty keys to an element you want to focus.

                     WebElement element  = driver.findElement(By.id("element-id"));
                           //Send empty message to element for setting focus on it.
                   element.sendKeys("");


Overwrite Current Input Value On Page

The send Keys method on Web Element class will append the value to existing value of element. If you want to clear the old value. You can use clear() method. 

                   WebElement element = driver.findElement(By.id("element-id"));
                   element.clear();
                 element.sendKeys("new input value");

Mouseover Action to Make Element Visible Then Click

When you are dealing with highly interactive multi layered menu on a page you may find this useful. In this scenario, an element is not visible unless you click on the menu bar. So below code snippet will accomplish two steps of opening a menu and selecting a menu item easily.

               Actions actions = new Actions(driver);
               WebElement menuElement = driver.findElement(By.id("menu-element-id"));
           actions.moveToElement(menuElement).moveToElement(driver.findElement(By.xpath("xpath-of-menu-item-element"))).click();


Extract CSS Attribute of an Element

This can be really helpful for getting any CSS property of a web element.
For example, to get background color of an element use below snippet

           String bgcolor = driver.findElement(By.id("id123")).getCssValue("background-color");
  
and to get text color of an element use below snippet


           String textColor = driver.findElement(By.id("id123")).getCssValue("color");

Find All Links on the Page

A simple way to extract all links from a web page.
                      List link = driver.findElements(By.tagName("a"));

Take a Screenshot on the Page

The most useful one. Selenium can capture the screenshot of any error you want to record. You may want to add this code in your exception handling logic.

                  File snapshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


Execute a JavaScript Statement On Page

If you love JavaScript, you are going to love this. This simple JavascriptExecutor can run any JavaScript code snippet on browser during your testing. In case you are not able to find a way to do something using web driver, you can do that using JS easily.
Below code snippet demonstrates how you can run a alert statement on the page you are testing.

                 JavascriptExecutor jsx = (JavascriptExecutor) driver;
                jsx.executeScript("alert('hi')");

Upload a File on a Page

Uploading a file is a common use case. As of now there is not web driver way to do this, however this can be easily done with the help of JavascriptExecutor and little bit of JS code. 

                   String filePath = "path\\to\\file\for\\upload";
                  JavascriptExecutor jsx = (JavascriptExecutor) driver;
                      jsx.executeScript("document.getElementById('fileName').value='" + filePath + "';");
 

Scroll Up, Down or Anywhere On a Page

Scrolling on any web page is required almost always. You may use below snippets to do scrolling in any direction you need.

                   JavascriptExecutor jsx = (JavascriptExecutor) driver;
                  //Vertical scroll - down by 100 pixels
              jsx.executeScript("window.scrollBy(0,100)", "");
             //Vertical scroll - up by 55 pixels (note the number is minus 55)
            jsx.executeScript("window.scrollBy(0,-55)", "");
                     //Horizontal scroll - right by 20 pixels
                jsx.executeScript("window.scrollBy(20,0)", "");
               //Horizontal scroll - left by 95 pixels (note the number is minus 95)
               jsx.executeScript("window.scrollBy(-95,0)", "");

Get HTML Source of an Element on Page

If you want to extract the HTML source of any element, you can do this by some simple JavaScript code.

               JavascriptExecutor jsx = (JavascriptExecutor) driver;
                   String elementId = "element-id";
                   String html =(String) jsx.executeScript("return document.getElementById('" + elementId + "').innerHTML;");

Switch between Frames In Java Using Web driver

Multiple iframes are very common in recent web applications. You can have your web driver script switch between different iframes easily by below code sample

              WebElement frameElement = driver.findElement(By.id("id-of-frame"));
                driver.switchTo().frame(frameElement);

Can you think about any other common scenario that you used in web driver? Don’t forget to share with us in comments section below

Comments

Popular posts from this blog

BEST AUTOMATION TESTING TOOLS FOR 2018 (TOP 10 REVIEWS)

10 Remarkable Learning Quotes From 10 Astonishing People