Element not clickable at point Selenium Webdriver

Issue:

Element not clickable at point (x, y)

Reason:

This issue normally occurs if the target element is not clickable, which means that the element is not in the state of user interaction. This is due to the following reason
A.) Element is in list and is currently not in the view-able area of the browser

How To Fix

  1. (Case A)Scroll the page so the element comes in the viewable area of the browser
    for example:

    // Get the element
    WebElement targetElement = driver.findElement(By.id("itemid"));
    
    // Create the JavascriptExecutor object
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    
    // Scroll down the page to the element with JavaScript
    jse.executeScript("window.scrollTo(0,'+elementToClick.getLocation().y+')");// Click on the element
    targetElement.click();
  2. (General Case) This method doesn’t care about the current state of the target element. No matter if the element is at the bottom of the page and requires scroll to access it.
    So this method is a bit hackish since from the user point of view you cannot click(or interact with) an element if the element is present at the bottom of the page and requires some scrolling.

    In this method we use JavaScript to perform the click. This method will succeed as long as the element is present in the page.

    Here is how to do this:

    
    //Get the element
    WebElement we = driver.findElement(By.id("elementid"));
     
    // Create the JSExecutor object
    JavascriptExecutor executor = (JavascriptExecutor)driver;
     
    // Perform the click with javascript
    executor.executeScript("arguments[0].click();", we);

Selenium WebDriver Element is not visible error

Element is not visible error:

This error occurs when the target element is hidden below some other element (something like a dialog box) or it is hidden by the CSS in the page. In this case we have two options:

  1. Remove or hide the other element so that the target element is visible and the perform events on it.
    For this get the element

    //Element
    
    WebElement we = driver.findElement(By.id("elementid"));
    //Hide the element
    ((JavascriptExecutor)driver).executeScript("arguments[0].style.display='none'", we);
    

    and remove it or hide it using JavaScript or by selenium.

  2. In case visibility of the element is not important and still some action needs to performed then with the help of JavaScript webdriver can perform the click event on the target element and the visibility of the element will be ignored.Here is how we can do this:
    //Element
    
    WebElement we = driver.findElement(By.id("elementid"));
    
    // JSExecutor 
    
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    
    // JS click 
    
    executor.executeScript("arguments[0].click();", we);

    This method works because the JavascriptExecutor object does not care whether the element is visible or not, but while doing it normal way the element needs to be visible.

Handling tinyMCE editor with Selenium Webdriver

Here is how to use Selenium Webdriver with tinyMCE:

The tinyMCE editor creates its own iframe, so before selenium is able to perform any task or action on it, it has to first switch the control to the iframe and then start execution.
Here is how to switch this:

// Select the iframe
driver.switchTo().frame("yourtxtarea_ifr");
// select the editor nad do the input 
 driver.findElement(By.id("tinymce")).sendKeys("Dummy text");

Now after the WebDriver is all done with its actions on the editor it needs to switch back to the default window to continue with the rest of the script. Below is the sample code to switch back to the default window:

// switch back to the default window 
driver.switchTo().defaultContent();

Hope this helps. Please let us know in case of any issues.

Selenium Explicit and Implicit Waits

Waits

To wait means having the task to stop execution for a certain amount of time. After the the time is elapsed the execution continues with he next steps. Selenium API provides two flavours of waits: Explicit Wait and Implicit Wait.

Explicit Wait

Explicit Wait is the code to stop execution for a certain time until an expected condition is met. The expected condition may be the presence of any element of the visibility of the element. As soon as the expected condition is evaluated to be true the execution resumes. For instance, if an explicit wait of 10 seconds is set and we want to stop the execution until an element is present on the page, the WebDriver will on every 500 miliseconds check to see if the element is present on the page or not. If the element is found(i.e., the condition becomes true before 10 seconds), the execution will resume. In case the condition is not met and the time(10 seconds in this case) has elapsed the TimeoutException is thrown. There are few convenience method provided by the API to implement the expected conditions.

Using presenceOfElementLocated

WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com");
WebElement element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("some_element_id"))); //Element is present

Using elementToBeClickable

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("some_element_id"))); //Element to be displayed and enabled to be clicked

Another way to implement the explicit wait is to use the Thread.sleep() (not recommended) method, which will cause the current Java Thread to stop execution for a certain amount of time. Note that this is not a preferred way to implement explicit wait as it can cause the task to run into deadlock and other threading related issues.

Implicit Wait

Implicit wait is a way to tell the driver to look into the DOM for an element for certain amount of time if the element is not available immediately. By default the time for the implicit wait is 0 seconds. This implicit time can be changed and once changed it will be used till the life of WebDriver object. Of course this can again changed later the same way it was set earlier. Implicit wait especially usefull when the elements are created dynamically on the page, a modal box, for example. Below is an example of setting the implicit time wait.

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.example.com");
WebElement element = driver.findElement(By.id("some_element_id"));

In the above example please note that the implicitlyWait() method takes the two arguments the first is the amount of time and the second is the unit of time. Hence the above example will set the implicit wait to 10 seconds. This way the findElement() will not return immediately if the element is not found, instead it will wait for 10 seconds for the element to be present and in between the waiting it will keep polling (after every 500 milliseconds) the DOM for the element. As soon as the element is present it will be returned.

Selenium Page Interactions and Actions API

Interactions

A Note Before Interactions

Slow Network Connections are evil for Selenium

Since right the after the statement to load the page the element is not displayed, because the page might not have been loaded fully depending upon the network connection speed. If this is the case then the best way to deal with this issue is to wait for some time so that the page loading is completed and the element is properly displayed and is ready to be interacted.

Also sometimes even if the element is present in the page but to make it visible the browser might take some time or the element’s visiblity might depend on some event on some other element, modal boxes are the best examples of this case. If the element is not visible the driver throws the ElementNotVisibleException. The reason why the WebDriver throws this exception is because from a user’s perspective an element cannot be interacted with if it is not visible to the user.

Here by visibility we mean that the CSS “display” property is set to be “none” not the CSS visibility property. For this all we need to do is add an explicit wait condition for the element to be visible.
But there are JavaScript hacks available to interact with element even if it is not visible.

Now since we have seen how to select elements on page we are ready to interact with them. These interactions are just the actions (JavaScript events) what a normal user would like to perform on elements of the page. Below is a list of most common interactions/actions/events that are supported by the Selenium API.

click()

Click is probably the most common action performed by a user. It simulates the same click event that triggers when a user of the web application clicks on any element.
We have already seen several previous examples similar to code below:

WebElement element = driver.findElement(By.id("some_id"));
element.click();

sendKeys()

This method enters a string of text into input fields or text area. Below is an example:

WebElement element = driver.findElement(By.id("input_field_id"));
element.sendKeys("Some Text");

submit()

The submit() method is used for form elements like an input box. When a submit() method is called on an element the driver traverse upward in the HTML and tries to find a form element and triggers submit on the form. If the form element is not found it throws the NoSuchElementException. Below is an example:

WebElement element = driver.findElement(By.id("input_field_id"));
element.submit();

getText()

As the name suggests the getText() method returns the text content from the specified element.



WebElement element = driver.findElement(By.id("input_field_id"));
String content = element.getText();

Scrolling

At numerous times user might need to scroll down the page to locate some element. For this JavaScriptExecutor class can be utilized. Below is an example of that. The scrollTo() method of window object takes two parameters: 1.) horizontal location from left size of the page (in pixels) and 2.) vertical location from the top of the page(in pixels). In the code below the horizontal argument is set to 0(assuming there is no horizontal scroll in the page) and the vertical argument to element’s vertical position from top.

// Get the element WebElement targetElement = driver.findElement(By.id("itemid"));
// Create the JavascriptExecutor object
JavascriptExecutor jse = (JavascriptExecutor)driver;
// Scroll down the page to the element with JavaScript
jse.executeScript("window.scrollTo(0,'+targetElement.getLocation().y+')");
// Click on the element
targetElement.click();

Drop Down/Select Options

Selenium provides a class for the select element and three different methods to choose the option.

Select select = new Select(driver.findElement(By.id("element_id")));
//Method 1
select.selectByIndex(1); //0 based indexes
//Method 2
select.selectByValue("option_value");
//Method 3
select.selectByVisibleText("text_on_option");

Firing JavaScript Events

Consider following HTML:

<a href="www.example.com" onclick="doSomeAction();">Link Text</a>

In the above code, since it is an anchor tag, the click event does not fire hence the method the doSomeAction() does not get executed, based on different browsers event handling mechanisms.
To handle this kind of situations, the JavaScriptExecutor can be used.

executor.executeScript("arguments[0].click();", element);

Selenium RC support: Selenium RC provided support for JavaScript firing events, but in Selenium 2.0 the functionality was not included. Here is how it worked in Selenium 1.0:

Selenium selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.example.com");
selenium.fireEvent("link=Link Text", "click");

AdvancedUserInteractions API

The AdvancedUserInteractions API provides support for more advanced user interaction. It can be a drag and drop event or selecting(clicking) multiple elements while holding the Control key. Below are examples of drag and drop event and the Clicking multiple elements while holding the Control key.

Drag and Drop

To enable an element to be dragged and dropped on some other element the Selenium API provides the dragAndDrop() method from the Actions class.

WebElement elementToBeDragged = driver.findElement(By.id("id1"));
WebElement targetElement = driver.findElement(By.id("id2"));
(new Actions(driver)).dragAndDrop(elementToBeDragged, targetElement).perform();

Simulating Sequence Of Events

The Actions class can be used to simulate multiple events at a time(for example, selecting multiple files by clicking, while holding the CTRL key). The code below uses multiple events to simulates the same action.

Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.click(someOtherElement)
.keyUp(Keys.CONTROL);
Action selectMultiple = builder.build();
selectMultiple.perform();

Single Actions

Below is a list of the actions supported by the API.

  • ButtonReleaseAction – Releasing a held mouse button
  • ClickAction – Equivalent to WebElement.click()
  • ClickAndHoldAction – Holding down the left mouse button
  • ContextClickAction – Clicking the mouse button that (usually) brings up the contextual menu
  • DoubleClickAction – double-clicking an element
  • KeyDownAction – Holding down a modifier key
  • KeyUpAction – Releasing a modifier key
  • MoveMouseAction – Moving the mouse from its current location to another element
  • MoveToOffsetAction – Moving the mouse to an offset from an element (The offset could be negative and the element could be the same element that the mouse has just moved to)
  • SendKeysAction – Equivalent to WebElement.sendKey(…)

We are ready to take a look at the Selenium Explicit and Implicit Waits. Let us know any issues regarding the above topic.

Selenium Element Selectors

To perform operations and tasks on webpage and or elements of the page, the selenium script requires to be aware of the element on which the operation is to be performed. Selenium provides a range of element selection method for that purpose. We will be looking at the most commonly used ones.

Selectors

Selenium generally selects elements in a very similar way that HTML provides through CSS and JavaScript. For example elements can be selected through their “id” or their “className” or simply their names. WebDriver uses various method provided byt the By class like By.id(). Below are some selectors that are used by WebDriver for selecting the elements.

  • By.id()

    Using this method elements are selected by their id.

    WebElement element = driver.findElement(By.id("submit"));
    element.click();
  • By.tagName()

    Using this method elements are selected by the element’s tag name.

    WebElement element = driver.findElement(By.tagName("button"));
    element.click();
  • By.className()
    Using this method elements are selected by their className attribute. Notice that this method is used with the “driver.findElements()” as the “className()” method is expected to retur a list of webElements and to access each element driver has to iterate through the list.

    
    List  nameElements = driver.findElements(By.className("first-name"));
    Iterator  nameIterator = nameElements.iterator();
    while (nameIterator.hasNext()) {
        System.out.println(nameIterator.next().getText());
    }
    
  • By.name()
    Using this method elements are selected by their name.

    
    WebElement element = driver.findElement(By.name("q"));
    element.sentKeys("Some Text");
    
  • By.linkText()
    Using this method link elements are selected by matching the visible text of the element.

    
    WebElement element = driver.findElement(By.linkText("Selenium Learning"));
    element.click();
    
  • By.partialLinkText()
    Selecting a link element by matching partial visible text of the element.

    WebElement element = driver.findElement(By.partialLinkText("Selenium"));
    element.click();
    
  • By.css()
    Selecting element by css selection method

    WebElement element = driver.findElement(By.partialLinkText("#main-content div.heading"));
    element.getText();
    
  • By.xpath()
    Selecting element by the xxapth of the element. This method is not very promising since the x path of some element can change is the web page adds elements dynamically and its working differs on different browsers.

    
    List  elements = driver.findElements(By.xpath("//*[@id="side"]/div[2]/div/ul/li/ul/li[3]/a"));
    
  • JavaScriptExecutor
    Selenium provides a JavaScript way to do things. The Selenium API provides a JavaScriptExecutor wrapper to execute This method doesn’t care about the current state of the target element. No matter if the element is at the bottom of the page and requires scroll to access it. So this method is a bit hackish since from the user point of view you cannot click(or interact with) an element if the element is present at the bottom of the page and requires some scrolling. In this method we use JavaScript to perform the click. This method will succeed as long as the element is present in the page. The “arguments[0]” represents the element to be used by JavaScript.

    
    WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('#control')[0]");
    
  • Selection Windows/Frames
    Sometimes a test may need to open up a new window or frame and to continue with operations of them requires the WebDriver to be told to switch between them. Selenium provides API for that and below is an example of it.

    driver.switchTo().window("windowName");
    

    If the webpage has an iframe embedded into it by default the scripts executes on the main window. Below is how to execute script in the frame

    
    driver.switchTo().frame("frameName");
    

    To switch back to main window following code can be used

    
    driver.switchTo().defaultContent();
    
  • Handeling alerts/confirmation popups
    To handle alert or confirmation boxes the switchTo() method can be used. Below is an example for accepting(confirming i.e., clicking on “OK”) a confirmation/alert popup.

    
    Alert alert = driver.switchTo().alert();
    alert.accept();
    

    To reject a confirmation box(i.e., clicking “Cancel” or “NO”)

    
    Alert alert = driver.switchTo().alert();
    alert.dismiss();

Selectors above are the most commonly used ones and are enough to perform action on a well structured web page.

Simple Selenium Webdriver Example in Java

After Setting up the environment we can now go ahead and write some sample code. We will be using Java for this purpose.

Take a look at the code example below and afterwards we will try to understand the working


import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SimpleExampleTest {
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "https://www.google.co.in";
        driver.get(baseUrl);
    };

    @Test
    public void testSimpleExample() throws Exception {
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("selenium");
        element.submit();
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
              public Boolean apply(WebDriver d) {
                  return d.getTitle().equals("selenium - Google Search");
              }
          });
        driver.findElement(By.linkText("Selenium - Web Browser Automation")).click();
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
              public Boolean apply(WebDriver d) {
                  return d.getTitle().equals("Selenium - Web Browser Automation");
              }
          });
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
}

Explaination

The above example searches for the text “selenium” in Google and clicks on of the search results. If the browser finally arrives to the right page (decided by the page title) we say the test is successful.

Annotations

For those who are not much familiar with the annotations the @Before makes sure that a method is called before every test, similarly @After makes sure that a method is always called after every test method which is denoted by @Test annotation. So the sequence in the above example will be: setUp() >> testSimpleExample() >> tearDown(). If we had another test method (say) testAdvancedExample then the order will be setUp() >> testSimpleExample() >> tearDown() >> setUp() >> testAdvancedExample() >> tearDown()

The setUp() method

This method initializes the driver and the baseUrl variables in first two lines and opens the web page pointed by thebaseUrl variable. The driver variable is initialized for the Firefox browser, so the test will be run on the Firefox. If the test is to be run on Google Chrome chromedriver executable should be downloaded and its path has be added to the PATH variable in the system. To programatically set the chromedriver path for individual scripts the following code can be used:

<pre><code>

System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver_dir\\chromedriver.exe”);
driver = new ChromeDriver();

</code></pre>

The testSimpleExample() method

As the name suggests this method is the actual test to be performed. Here is the line by line explanation:

  • The very first line of the method finds the element by the name given to it, in this case it is an input fields whose name is “q” and saves it to the element variable of class WebElement.
  • Next it submits the form(only since the element is inside the form element).
  • In the next line the script waits for 10 seconds by creating a WebDriverWait object. The driver waits for 10 seconds or until the the expected condition specified in the until() method is met. In this case the expected condition is to check the equality of the page title and the text “selenium – Google Search”. Which ever happens first either the 10 seconds time or the condition, the driver resumes the execution. Between this wait the driver on every 500 milliseconds check for the condition to be met. The wait is provided because the the browser may take time to get the search results based on the network connection speed.
  • Next it finds an element by its link text and clicks on it.
  • Once again a time wait is created to see if the browser has opened right page by matching its title witht the text “Selenium – Web Browser Automation”.
  • If any of the above conditions fails the test is said to have failed.

The tearDown() method

This method simply frees the resources held for the test, i.e., closes the browser by calling the driver.quit() method.To perform all the above interaction the Selenium API provides various methods to select the elements on the page. Take a look at various selection method on the Element Selection page.