DEV Community

Tony Colston
Tony Colston

Posted on

CSS selector locators

Another way to find an element on a web page in Selenium is using a CSS selector.

Again ID or Name are generally your best bet for locating elements in Selenium but a CSS Selector can be powerful too.

A CSS Selector can use the ID attribute too. I will show that below as an example. So if you have some front development and understand CSS Selectors then using mostly CSS Selectors as Selenium locators will be a good choice.

If you do not know CSS Selectors that well you can use Chrome devtools to find them easy peesy.

Go to inspect and the find the element you want. Right click on the element and select Copy... then choose selector.

Here is what a CSS Selector will look like in a Python Selenium script.

        selector_path = "#form > main > div:nth-child(2) > section > section > section.hero-lockup > div > section > span.triptych-item.screenshots > div.triptych-item-meta > p > strong > span"
        e = driver.find_element(By.CSS_SELECTOR, selector_path)
Enter fullscreen mode Exit fullscreen mode

Sometimes the CSS Selector will effectively be the ID. As an example the dev.to button "Write a Post" CSS Selector is shown below.

#write-link
Enter fullscreen mode Exit fullscreen mode

If you use a CSS Selector and the DOM structure changes then it is possible your locator will fail and as a result your test will fail too. You should try to pick the most specific CSS Selector you can (aka ID or name) to help mitigate this problem.

A good reference from MDN on CSS selectors can be found here: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors

Top comments (0)