Thursday, August 14, 2014

Easy way to determine the better XPath for Selenium Webdriver scripts

Determine the best XPath for selenium webdriver is sometimes difficult. We use different tools like Fire Bug, XPath checker, XPath Hepler for Chrome, developer tools for different browser etc. But determine the accurate XPath which will work every time when scripts runs, is sometimes difficult. It is found that proper XPath has constructed using a tool and implemented in the script to find the element and run the script multiple times at the time of development so that no “element not found” found but at the time of test execution it cannot detect the element. In that case we need to change the XPath again and run again to check that it is working.
But if we use the XPath that is  nearly better and developed by some of the Selenium tools like Selenium IDE, is more better than any other tools and nearly well known for Selenium webdriver API.
Here I will show you how to determine XPath for Selenium Webdriver scripts to locate element in the web page by using our well known Selenium IDE tools.

Installing the IDE tools:
You may know How to install Selenium IDE Plug in on your Firefox Browser. If not then click here.

Determining the XPath:
Step 1: Open Firefox browser.
Step 2: Click on the Selenium IDE icon on Plug in tool bar.

image

Step 3 : Selenium IDE window is displayed. Now click the red color record button to make the record on.

image

Step 4 : Now minimize the IDE window and enter the application URL : https://www.google.com.bd/ at the Firefox browser
Step 5 : Enter the text “Selenium IDE” at Google search text box and click on Search button.
Step 6 : Now Restore the Selenium IDE window and click red color button again to Stop the recording. You can play the script by clicking on green color play button.
Step 7 : Click on a Step. Command, Target and value is displayed at the bottom of the window.

 image

Step 8 : Here we see “id” as a locator in target combo box. If we click on the combo box we see a drop down list of other locators like Name, CSS, XPath etc.

image

Step 9 : There are three types of XPath here – Attribute, relative and Position. Most of the cases position is working fine. We select the XPath : Position at the target combo box. Now click on “Find” button to verify that it can locate the actual element.

image

Step 10 : Copy the XPath from Target box and paste to the selenium Webdriver code as Locator.
C# :
driver.FindElement(By.XPath("//td[2]/div/input")).SendKeys("Selenium IDE");
Java :
driver.findElement(By.xpath("//td[2]/div/input")).sendKeys("Selenium IDE");
Note that we will only use XPath if and only if id, Name or CSS are not available as locator. 
Thanks!!!