In order to click on or type into an HTML element, first you need to locate that element. The easiest way to get started with locators in Selenium is probably XPATH. It is something like three clicks: Right click, inspect element, look in the developer toolbar, right click, copy XPATH (the ‘Copy XPath’ option is hidden under the Copy submenu within the context menu).
Changing selectors from XPATH to CSS can not only make them faster, but less brittle and easier to read. The best approach might be to know both well.
Let’s talk about how to change selection strategy from XPATH to CSS.
Google’s homepage currently has a large text input, with a name of “q.” The simplest xpath for this is a match:
//input[@name="q"]
The CSS is very similar:
input[name=q]
Here are examples selecting the element in Ruby using Webdriver 3.0.
driver = Selenium::WebDriver.for :chrome, options: options
driver.navigate.to "http://google.com"
element = driver.find_element :xpath, '//input[@name="q"]'
element = driver.find_element :css, 'input[name=q]'
HTML is built like a tree, with child nodes below parents. A child in XPATH is represented with a "/", as it is with directories on UNIX filesystems. In CSS the child is indicated with a “>” Examples of a link (“a”) inside of a div tag:
In XPATH: //div/a
In CSS: div > a
Sometimes an element is inside another, perhaps several levels down - and the author does not wish to write /div/div/div/div. In that case, a lazy match of any subnode can be defined in XPATH using two slashes, or "//". In CSS just by a whitespace Examples:
In XPATH: //div//a
In CSS: div a
ID’s in XPATH and CSS are similar to names. XPATH defines ID’s using: "[@id='example']" while another approach in CSS is to use the pound sign,or "#" Examples:
In XPATH: //div[@id='example']//a
In CSS: div#example a
For class, things are pretty similar in XPATH: "[@class='example']" while another option in CSS is the dot "." Examples:
In XPATH: //div[@class='example']//a
In CSS: css=div.example a
That's enough for now. As you can see, the first rules are straightforward and can make locators shorter and, cleaner. The best option is probably to be fluent in both. Our next tip will cover advanced concepts in element locators. In the meantime, check out the Molliza description page on the topic.