Tuesday, 20 June 2017

Implicit wait vs Explicit wait in Selenium Webdriver

Implicit wait is used to wait for fixed duration for all elements to be available.
But ideally not all elements need fixed amount of time. Some elements may need 2 sec while some elements may need 50 seconds.


So I never recommend my team members to use the implicit wait. We should always use explicit wait conditions which helps us specify different timeouts for each element seperately.

You should never use implicit wait and explicit wait together. If you use them together, you will end up encountering unexpected timeouts in your application.
For example - if you have set the implicit wait to 20 seconds and for a specific element you have used the explicit wait, then explicit wait will only work if element is available in page. Explicit wait will not work as expected when element is not available on page.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Friday, 8 July 2016

How to extract digits from a String in Java

Many times, we have to verify the numbers from a given string.

Below Java code will help get the digits from the string.

public String extractDigits(String str){
       return str.replaceAll("[^0-9]","");
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Monday, 4 July 2016

How to auto download a file in Selenium

When you try to download a file from a website in Selenium, window dialog may appear. But Selenium can not handle such native windows. We may use AUTOIT scripts for handling native windows. But that's only possible on Windows OS.

Better solution is to change the driver settings so that file is automatically downloaded to system bypassing the File save dialog.

If you are using Firefox, you can use below code to start the driver with below profile.

FirefoxProfile myprofile= new FirefoxProfile();
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "c:\\mydownloadlocation\\xyz");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
WebDriver driver = new FirefoxDriver(myprofile);

If you are using Chrome driver, you can use below code to skip the download window.

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.prompt_for_download", false);
        prefs.put("download.default_directory", "path-to-download-directory");
        options.setExperimentalOption("prefs", prefs);
        WebDriver driver = new ChromeDriver(options);

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to find total number of rows and columns in a table in Selenium

We can use below XPATH expressions to find count of rows and columns in a table.

  1. //table//th  - Find total number of columns in a table. Note that this will only work if all columns are marked using th tag
  2. //table//tr - Find total number of rows in a table.
  3. //table//tr[1]//td - Find total number of TD tags inside a given table row. 

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to verify if text is present on a web page in Selenium

We can use below xpath selector to verify if the text is present on a web page in Selenium.

//*[contains(text(),'text data')]

Note that above xpath will identify text wrapped in any element like div, span etc.
Only condition is that text should be inside one specific tag.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to clear data from a text box using JavaScriptExecutor in Selenium

Sometimes, clear method does not work. It does not clear the data from text box. In those situations, we can use Java Script to clear the data.
Below line clears the data from edit box.

((JavascriptExecutor) driver).executeScript("arguments[0].value ='';", element);

Note that second parameter is the name of Web Element (Text box).

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday, 2 July 2016

Selenium IDE Add-On for Firefox

Selenium IDE is a Firefox Add-On that can be used to record and playback the Selenium scripts. We can also export the scripts to various programming languages like C#, Java, Ruby and Python.

You can download the Add-On XPI file from the link - https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/

Next you can install the Add-On in Firefox. Once installation is successful you will notice the Selenium IDE menu in Tools as shown in below image.

Selenium IDE menu

Below image shows the Selenium IDE GUI. We can record the script by clicking on red circle icon.


Below image shows that we can export the recorded script to Ruby, Python, Java, C# etc.




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Limitations of Selenium WebDriver

Even though Selenium is the most popular automation testing tool, it has got below limitations.

  1. We can only test web applications. We can not test desktop based applications. 
  2. We can test mobile applications but we need to use the Appium for that.
  3. We can not automate the CAPTCHA 
  4. We can not automate the complex control like Flash, Silver light Components, Applet controls, native window dialogs etc
  5. We often encounter issues like Selenium not launching latest browsers due to incompatibility issues. In such scenarios, we have to downgrade the browser in order to automate it.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Selecting drop down value using JavaScript in Selenium

In some web applications, when we select a value from the drop down, new controls or elements appear or disappear on the webpage. In short, change event is fired. But sometimes, change event does not get fired after selecting the value from drop down using selenium.

In such scenarios, we can use JavascriptExecutor to fire the change event on drop down element as shown in below code.

protected void fireChangeEvent(WebElement element){
        ((JavascriptExecutor) driver).executeScript(" var evt = 
document.createEvent('HTMLEvents'); evt.initEvent('change',true,true); 
arguments[0].dispatchEvent(evt);",element);
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Enter data in text box using JavaScript in Selenium

Sometimes, sendKeys method does not work on text boxes. In such scenarios, you can use JavascriptExecutor to set the value in edit box. Below method takes 2 arguments. It sets the value passed in second argument in text box identified as first parameter.

protected void setValueByJavaScript(WebElement element,String value) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].value ='"+
value+"';", element);
    }


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Setting up Selenium and Maven project

In Maven project, you can add below dependency and start writing the tests in JUnit or TestNG framework.

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
</dependency>

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Wednesday, 22 June 2016

Listeners in Selenium

When Selenium performs any of the operations like click, navigate etc, events are fired.
We can write custom code when these events are fired.

We will need to create a class that implements the methods to be called after event is fired.

Below class implements the WebDriverEventListener.

package chrometest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

/**
 * Created by Sagar on 22-06-2016.
 */
public class ListenerImplementation  implements WebDriverEventListener {
    @Override
    public void beforeNavigateTo(String s, WebDriver webDriver) {
        System.out.println("Before navigating to " + s);
    }

    @Override
    public void afterNavigateTo(String s, WebDriver webDriver) {

    }

    @Override
    public void beforeNavigateBack(WebDriver webDriver) {

    }

    @Override
    public void afterNavigateBack(WebDriver webDriver) {

    }

    @Override
    public void beforeNavigateForward(WebDriver webDriver) {

    }

    @Override
    public void afterNavigateForward(WebDriver webDriver) {

    }

    @Override
    public void beforeFindBy(By by, WebElement webElement, WebDriver webDriver) {
        System.out.println("Before find by");
    }

    @Override
    public void afterFindBy(By by, WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeClickOn(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void afterClickOn(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeChangeValueOf(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void afterChangeValueOf(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeScript(String s, WebDriver webDriver) {

    }

    @Override
    public void afterScript(String s, WebDriver webDriver) {

    }

    @Override
    public void onException(Throwable throwable, WebDriver webDriver) {
        System.out.println("Exception");
    }
}

Next we need to register the instance of this class with driver as shown in highlighted code below. beforeNavigateTo method is called when execute below code. In fact, all the methods for corresponding events are called automatically.

package chrometest;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import java.util.concurrent.TimeUnit;
/** * Created by Sagar on 17-02-2016. */
public class LaunchEventFiringChrome {
    static WebDriver driver = null;

    @Test    public void launchChromeTest() throws Exception{
        System.setProperty("webdriver.chrome.driver",
 "C:\\Users\\Sagar\\Videos\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        EventFiringWebDriver eventFiringWebDriverDriver  =
 new EventFiringWebDriver(driver);
        ListenerImplementation listenerImplementation = 
new ListenerImplementation();
        eventFiringWebDriverDriver.register(listenerImplementation);

        eventFiringWebDriverDriver.manage().timeouts().implicitlyWait
(10, TimeUnit.SECONDS);
        eventFiringWebDriverDriver.manage().window().maximize();
        String domain = "http://www.softpost.org";
        eventFiringWebDriverDriver.get(domain);
        System.out.println(eventFiringWebDriverDriver.getTitle());
        eventFiringWebDriverDriver.close();
        eventFiringWebDriverDriver.quit();

    }
}

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

RemoteWebdriver in Selenium

You will need to use RemoteWebdriver if you want to connect to selenium server. We pass the capabilities to remote server which passes the commands to appropriate machine where the driver with given capabilities is available.

RemoteWebdriver is mainly useful when you are using Selenium Grid or running tests in Cloud.
One of the constructors of RemoteWebdriver takes 2 parameters - url of selenium server and capabilities

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Tuesday, 21 June 2016

Headless execution using HTML Unit in Selenium

Headless mean without any user interface. HtmlUnit allows you to execute tests in Headless manner. You will not see browser opening the web pages or performing any operation like clicking buttons or entering data. All these operations happen in memory. This kind of execution is useful if you want to test the functionality. Also headless execution is much faster than normal execution. Downside is that you will not be able to test how the web page actually looks like on specific browser.

You will have to add below dependency in your project.

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

By default, JavaScript is not enabled. You need to use below line to execute JavaScript.
((HtmlUnitDriver)driver).setJavascriptEnabled(true);

Here is the complete code to execute selenium tests using HtmlUnitDriver.

package htmlunit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

/**
 * Created by Sagar on 21-06-2016.
 */
public class testHtmlUnit {
    public static void main(String[] args) {
        WebDriver driver = new HtmlUnitDriver();
        ((HtmlUnitDriver) driver).setJavascriptEnabled(true);
        driver.get("http://www.softpost.org");
        driver.close();
        driver.quit();
    }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Resizing and moving browser window in Selenium

To resize the browser window, we can use below line. Dimension constructor takes 2 parameters - Height and width of the window.

driver.manage().window().setSize(new Dimension(100,100));

To set the browser window position, you can use below line of code. Point constructor takes 2 parameters - X and Y co-ordinates of the browser window. Below statement will move the window down by 200 pixel.

driver.manage().window().setPosition(new Point(0,200));

To maximize window, you can use below line of code.

driver.manage().window().maximize();

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Switching to default content in Selenium

A browser window can have multiple frames inside it. A frame can have multiple child frames inside it.

Suppose there are 2 frames with names f1 and f2 at the top level. There is one child frame with name cf1 inside frame f1. To switch to frame cf1, you will have to use 2 lines of code.

//After below statement is executed, context is switched to frame - f1

driver.switchTo.frame("f1");

//Now we are inside frame f1. To switch the context to child frame - cf1, we will have to use below command.

driver.switchTo.frame("cf1");

Now we are inside frame cf1.  

To switch the context to default content (main window content), you can use below line.

driver.switchTo().defaultContent();

Notice that while switching to the child frame - cf1, we have to switch the context to each parent frame. But to switch the context to main window, we can directly use defaultContent() method.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Comparison between Selenium and Appium

Here is the comparison between Selenium and Appium
  1. Selenium is an open source tool to test web applications running in desktop browsers. Appium is an open source tool to test the web applications running in mobile browsers. Appium also supports automation of native and hybrid mobile applications developed for iOS and Android OS. Appium uses selenium API to test the applications.
  2. Appium wraps vendor specific API into Webdriver API which is common for automating all types of mobile browsers. For example - Android API is different than iOS API. But Webdriver API is same. That's what Appium does for you!
  3. Appium can be used to test applications on various devices and platforms like Android phones, Apple iPads, Apple iPhones etc
Below image shows the difference between Selenium and Appium.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Comparison between Selenium and LeanFT


Here is the main difference between Selenium and LeanFT
  1. Selenium is open source. LeanFT is licensed tool developed by HP
  2. Selenium can be used to automate only Web applications. LeanFT can be used to automate web as well as desktop applications
  3. Selenium uses the locators like XPATH, CSS. LeanFT uses properties and value pairs. But we can also use XPATH
  4. Selenium is better in cross browser testing than LeanFT
  5. Both are platform independent. 
  6. LeanFT scripts can be developed in only Java and C#. Selenium scripts can be written many languages like Java, C#, Perl, PHP, Python, Ruby, JavaScript etc.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Monday, 20 June 2016

Launching Safari browser using Selenium

Before automating the Safari Browser, ensure that you do below settings.

  1. Create Safari Extension developer certificate on Apple developer website.
  2. Install webdriver extension in Safari Browser. You can download webdriver extension http://selenium-release.storage.googleapis.com/index.html?path=2.48/
Below image shows the sample extension on the google site.




Below code will launch the Safari browser.

Webdriver driver = new SafariDriver();                
driver.get("http://www.softpost.org");


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Launching Microsoft Edge Browser using Selenium

We can launch the Microsoft Edge Browser using below code. Note that you will have to download the Microsoft Edge driver from the link -  https://www.microsoft.com/en-us/download/details.aspx?id=48740 and set the property - webdriver.edge.driver in code. Also make sure that you are aware of IE settings required for Selenium.


package msedgetests;

import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import java.util.concurrent.TimeUnit;

/**
 * Created by Sagar on 19-02-2016.
 */
public class LaunchEdge {

    @Test
    public void launchEdgeBrowser() throws Exception{
        WebDriver driver = null;

       System.setProperty("webdriver.edge.driver",
        "C:\\Program Files (x86)\\Microsoft Web Driver\\MicrosoftWebDriver.exe");

        driver = new EdgeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        String domain = "http://www.softpost.org";
        driver.get(domain);
        System.out.println(driver.getTitle());
        driver.close();
        driver.quit();
    }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Buy Best Selenium Books

Contributors