How to find XPath/CSS selector in chrome and evaluate it with example

Finding XPath or CSS selector is very crucial task for selenium webdriver test script preparation and so google chrome has made it very easy for all and specially selenium users. There are many different chrome extensions available which provides this feature. But Google chrome's inbuilt Chrome Devtool is very easy to use. It has many other features as well but we will look at only XPath and CSS selector finder for now. Let's look it step by step.

Finding XPath/CSS selector of web element in chrome

Step 1 : First of all, Open your web page in google chrome browser. I will use http://only-testing-blog.blogspot.com/2014/01/textbox.html for this example. Here, we are going to find XPath and CSS selector of radio button with label Male.

Finding XPath of web element in chrome

Step 2 : Now press F12 button from your keyboard. It will open Chrome Devtool at bottom of the screen with Elements tab selected by default.

Step 3 : Now click on element inspector icon in Chrome Devtool. It will enable element inspector for chrome devtool. You will find it at top left side of Chrome Devtool.

enable element inspector in chrome devtool

Step 4 : Now move mouse at targeted web element(i.e. Radio button Male here) and click on it. It will highlight radio button's HTML in Elements tab. 

inspecting element in chrome devtool for xpath

Step 5 : Right click on highlighted HTML of element and navigate to Copy. Here you will find Copy XPath option to copy XPath of selected element and Copy Selector option to copy CSS path of targeted element.

copy element's xpath

We got #radio1 as CSS selector and //*[@id="radio1"] as an XPath of Male radio button in our example. So this is very simple and easy way of finding XPath and CSS selector of any web element.

Evaluating XPath or CSS selector

Due to the some reason, XPath or CSS selector of element which you have provided in your test script is unable to find that element when you run selenium webdriver test script. It will create confusion that element locator which you have used is incorrect. Chrome devtool will help you in XPath or CSS selector evaluation. Let's see how we can do it.

Step 1 : Open chrome devtool using F12.
Step 2 : Press CTRL + F. It will open DOM search under chrome devtool.

open dom search in chrome devtool


Step 3 : Type your XPath or CSS selector in DOM searching panel which you wants to evaluate. It will highlight element on page as well as HTML part in Elements tab if your given XPath or CSS selector is correct.

evaluate XPath or CSS selector in chrome dev tool


I think, This is enough to find and evaluate any XPath or CSS selector of any web element in google chrome.

No comments:

Post a Comment