Why Should We Learn XPath and CSS Selectors?
To automate our test cases we need to locate elements on a web page (Textbox, RadioButtons, Checkboxes, Dropdowns etc) and then perform actions based on test steps.
So far we’ve learnt 6 out of 8 ways to locate Web Elements on a page
- By.linkText(“HyperLink Text”)
- By.partialLinkText(“InComplete Link Text”)
Try writing selenium automation to fill the form below and click submit button.
What happened? Didn’t find unique way to identify the controls? It happens in real life too. That’s where XPath and CSS Selectors are helpful.
Understanding XPath and CSS Selectors.
There are two more ways to locate WebElement on a page
Concept is very simple – If HTML Code of a Page is considered as our laptop’s hard disk. Then each element is like a file stored on hard disk; And it can be identified by unique path.
For Example – See the HTML Page Code
Now Let’s see the XPATH and CSS Selector for img WebElement
// XPath of img element on web page. html/body/div/img // CSS Selector of img Element html > body > div > img
CSS and XPath just use different separators and notations for HTML Tags and Attributes. Learning that would simplify XPath and CSS Selectors.