- Selenium Tips: CSS Selectors
- Getting Started with CSS Selectors
- I: Simple
- Id
- Selenium XPath Css Selector Example
- 1. This Example Will Use The Below Html File Content.
- 2. Locate Web Element By XPath Example.
- 3. Locale Web Element By CSS Example.
- 4. Find Web Elements By XPath & CSS Selectors With WebDriver Example Java Code.
- How to Write the Best XPATH and CSS Selectors for Your Web Scraper
- CSS Selectors and XPATH Link to heading
- CSS Selectors Link to heading
- XPATH Link to heading
- CSS Selectors Basic Link to heading
- #x Link to heading
- .x Link to heading
- x y Link to heading
- x, y Link to heading
- x + y Link to heading
- x > y Link to heading
- x ~ y Link to heading
- x[y] Link to heading
- x[y=’z’] Link to heading
- x:last-child Link to heading
- x:empty Link to heading
- XPATH Basic Link to heading
- / Link to heading
- // Link to heading
- //x[@id=’y’] Link to heading
- //x[@class=’y’] Link to heading
- //x | //y Link to heading
- //x[@y=’z’] Link to heading
- //x/y/z Link to heading
- //x/text() Link to heading
- //x/y[N] Link to heading
- 4 Basic Tips to Write Effective Selectors Link to heading
- XPATH and CSS Selector Generator Tools Link to heading
- Using XPaths and CSS Selectors
- Alternate Selector Types
- Finding a CSS Selector or XPath
- Validating CSS Selectors as Input and Click Functions for Journeys
- Testing in the Browser
- Additional Resources
- Related Articles
Selenium Tips: CSS Selectors
Learn about CSS rules and pseudo-classes to help you move your XPATH locators to CSS.
In order for Selenium or Appium to click on an element, type into it, or mouse in or out, the tool first needs to find the element. The WebDriver code library provides methods to do just that, such as findelement() or findelements(). These usually take a locator, which can be created by ID, XPATH Code, or Cascading Style Sheets (CSS). Getting the XPATH code can be as easy as selecting the element in developer tools or using something like Chropath. Fundamentally, XPATH is a query language for XML-like documents, such as web pages. It can be awkward to write, brittle, and even more awkward to reverse engineer. As a result, CSS has gained favor as the way to identify objects in WebDriver.
Like most powerful things, CSS has a bit of a learning curve. It’s certainly a lot more challenging than cutting and pasting from a tool. Yet if you invest the time in learning CSS Selectors, you can have more powerful bindings that are easier to read, less brittle, and slightly more closely integrated into the browser platform.
Today we’ll provide CSS rules, tips, and pseudo-classes to either get you out on the right foot, or, perhaps help you move your XPATH locators to CSS.
Getting Started with CSS Selectors
A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page. They are string representations of HTML tags, attributes, Id and Class. As such they are patterns that match against elements in a tree and are one of several technologies that can be used to select nodes in an XML document.
Today we’ll cover simple CSS selectors, then more advanced, then pseudo-classes, which are essentially powerful, built-in matching functions that reduce a search to just what you are looking for.
I: Simple
Id
An element’s id in XPATH is defined using: “[@id=’example’]” and in CSS using: “#” — ID’s must be unique within the DOM.
Selenium XPath Css Selector Example
In selenium, you can use id, name as a locator to find Web Elements accurately. But in some cases, the id is generated dynamically and the name is also not provided. So XPath and CSS selectors are the most efficient way to locate web elements in such scenarios. We will show you examples of using XPath and CSS selectors to find web elements in this article.
1. This Example Will Use The Below Html File Content.
.btnBackground < background-color : red; >.btnFont
2. Locate Web Element By XPath Example.
- By id : //*[@id=»userName»] .
- By name : //input[@name=»passwd»] . If there has two input text boxes with the same name “email” as the example code, we can use //*[@name=’email’][1] , the index starts from 1.
- By name and value : //input[@name=’email’][@value='[email protected]’] .
- By CSS style value : //input[@name=’email’][@style=’background-color: red’] .
- By complete match text : //span[.=’Email1′] .
- By partial match text : //*[contains(text(),’Email’)] .
- Case insensitive xpath use translate(): //*[contains(translate(text(), ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’, ‘abcdefghijklmnopqrstuvwxyz’), ‘EMaIl’)]
- By Html a tag href attribute: //a[@href=’forgetPassword.html’] .
- Click here to learn more about XPath functions.
3. Locale Web Element By CSS Example.
- CSS is the abbreviation of “Cascading Style Sheet“. It is used in Html to make web element’s layout and style beautifully.
- CSS selector is a path pattern that can use a web element’s CSS attribute to locate a web element in the web page.
- CSS selector is simpler and faster than XPath, especially in Internet Explorer.
- Syntax : tagName[attributename=attributeValue] .
- A dot (.) is used to refer to CSS class : input.btnBackground.btnFont .
- Hash(#) is used to refer to id : input#userName .
- By id : input[id=userName] .
- By name : input[name=passwd] .
- Get web element list with same name element : input[name=email] .
- By name and value : input[name=email][value='[email protected]’] .
- By CSS style : input[name=email][style=’background-color: red’] .
- By Html a tag href attribute: a[href=’forgetPassword.html’] .
- ‘^’ means the start of the string : input[name^=’em’] .
- ‘$’ means the end of the string : input[name$=’il’] .
- ‘*’ means contain the string : input[name*=’ai’] .
- Use child node selector : form>input[name*=’ai’] .
- Use “+” to locate two or more adjacent web elements: input#submitBtn+input[id=’resetBtn’] .
4. Find Web Elements By XPath & CSS Selectors With WebDriver Example Java Code.
public class TestXPathCssSelector < public static void main(String[] args) < WebDriver driver = new FirefoxDriver(); driver.get("file://C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/webdriver/TestXPathCssSelector.html"); ListlocatorList = new ArrayList(); By byUserNameId = By.xpath("//input[@id='userName']"); locatorList.add(byUserNameId); By byPasswordName = By.xpath("//input[@name='passwd']"); locatorList.add(byPasswordName); By byEmail1 = By.xpath("//*[@name='email'][1]"); locatorList.add(byEmail1); By byEmailNameAndValue = By.xpath("//input[@name='email'][@value='[email protected]']"); locatorList.add(byEmailNameAndValue); By byEmailNameAndStyle = By.xpath("//input[@name='email'][@style='background-color: red']"); locatorList.add(byEmailNameAndStyle); By byTextComplete = By.xpath("//span[.='Email1']"); locatorList.add(byTextComplete); By byTextPartial = By.xpath("//*[contains(text(),'Email')]"); locatorList.add(byTextPartial); By byForgetPasswordHref = By.xpath("//a[@href='forgetPassword.html']"); locatorList.add(byForgetPasswordHref); //Below are css selector example. By byCssResetClass = By.cssSelector("input.btnBackground.btnFont"); locatorList.add(byCssResetClass); By byCssUserNameHashId = By.cssSelector("input#userName"); locatorList.add(byCssUserNameHashId); By byCssUserNameId = By.cssSelector("input[id=userName]"); locatorList.add(byCssUserNameId); By byCssPasswordName = By.cssSelector("input[name=passwd]"); locatorList.add(byCssPasswordName); By byCssEmail = By.cssSelector("input[name=email]"); locatorList.add(byCssEmail); By byCssEmailNameAndValue = By.cssSelector("input[name=email][value='[email protected]']"); locatorList.add(byCssEmailNameAndValue); By byCssEmailNameAndStyle = By.cssSelector("input[name=email][style='background-color: red']"); locatorList.add(byCssEmailNameAndStyle); By byCssForgetPasswordHref = By.cssSelector("a[href='forgetPassword.html']"); locatorList.add(byCssForgetPasswordHref); By byCssEmailStartStr = By.cssSelector("input[name^='em']"); locatorList.add(byCssEmailStartStr); By byCssEmailEndStr = By.cssSelector("input[name$='il']"); locatorList.add(byCssEmailEndStr); By byCssEmailContainStr = By.cssSelector("input[name*='ai']"); locatorList.add(byCssEmailContainStr); By byCssEmailUseChildSelector = By.cssSelector("form>input[name*='ai']"); locatorList.add(byCssEmailUseChildSelector); By byCssEmailUseaAjacentlector = By.cssSelector("input#submitBtn+input[id='resetBtn']"); locatorList.add(byCssEmailUseaAjacentlector); for(By locator : locatorList) < TestXPathCssSelector.findElement(driver, locator); >driver.quit(); > private static void findElement(WebDriver driver, By locator) < ListeleList = driver.findElements(locator); int size = eleList.size(); if(size>0) < System.out.println("There has " + size +" web element located by " + locator.toString() + " exist."); >else < System.out.println("Web element located by " + locator.toString() + " do not exist."); >> >
How to Write the Best XPATH and CSS Selectors for Your Web Scraper
Selectors are one of the most important pieces of your scraper. Well-written selectors make your web scraper work efficiently and fast. When the website’s layout changes your scraper’s selectors need to be changed as well. Then, in a well-established scraping environment the only things that have to be changed are the selectors. In this post I will dig into CSS selectors and XPATH and share some good tips with you to write effective and fast selectors for your web scraper.
CSS Selectors and XPATH Link to heading
CSS Selectors Link to heading
Css selectors are widely used by frontend developers to associate css properties with their html elements. For web scrapers, we can use it to navigate in the structure of an html file. If you are a beginner scraper and you’re familiar with css then I suggest that you should use css selectors over xpath, though in some cases you have to use xpath.
XPATH Link to heading
Xpath is a specification which is created to help you navigate in any XML document so you can use it while you’re parsing an html file. Almost each html parsing or web scraping related library has Xpath support. It’s a more robust and powerful way to locate elements than css selectors.
CSS Selectors Basic Link to heading
#x Link to heading
.x Link to heading
Elements that has x class. Selects all elements that have x class
x y Link to heading
Element is a direct or non-direct descendant of x.
x, y Link to heading
x + y Link to heading
First element that is immediately preceded by x
x > y Link to heading
Element is a direct child of x.
x ~ y Link to heading
All elements that is preceded by x
x[y] Link to heading
Element that has y attribute.
x[y=’z’] Link to heading
Element’s y attribute is “z”.
x:last-child Link to heading
Elements that is the last child of its parent.
x:empty Link to heading
Elements that have no children.
XPATH Basic Link to heading
/ Link to heading
Start searching from root node.
// Link to heading
Start searching from the start of the document.
//x[@id=’y’] Link to heading
//x[@class=’y’] Link to heading
Elements that has y class.
//x | //y Link to heading
Selects elements that are x or y. Searching in the whole document.
//x[@y=’z’] Link to heading
Elements that has y attribute which are z.
//x/y/z Link to heading
Element is direct descendant of y and y is direct descendant of x.
//x/text() Link to heading
//x/y[N] Link to heading
The Nth y element that is a child of x.
4 Basic Tips to Write Effective Selectors Link to heading
- Be specific if necessary and at the same time use as short selectors as you can.
- Know the HTML structure of the website thoroughly. Take time to go over it.
- Maintain the selectors. If the layout changed you probably need to change your code.
- Write selectors for yourself. Try to avoid tools.
XPATH and CSS Selector Generator Tools Link to heading
It can take a lot of time to figure out and test your selectors especially if it is a large project. If you are not afraid of messy CSS Selectors or XPATH or simply you don’t want to waste time writing your own selectors you can use one of the amazing tools below to make your job easier. These tools will generate your desired selectors and xpath. Be aware that these tools don’t necessarily create the most readable and most efficient piece of code. Also, they sometimes generate wrong strings that doesn’t select what you need.
Using XPaths and CSS Selectors
Selectors are used to locate elements on a webpage. ObservePoint uses them to find items to click on, enter text into, and to do other interactions in Journey and audit actions. The default selector is an element’s ID but alternate selectors can be used to increase the likelihood of a successful Journey when there is no ID on the target element.
Alternate Selector Types
The name attribute of an HTML element can be used as a selector.
Cascading Style Sheet (CSS) selectors is a syntax used in style definitions to locate items on a web page and apply styling to them (color, font family, positioning, etc). These selectors can also be used with jQuery to locate HTML elements.
XML Path Language (XPath) is a syntax for locating elements in structured documents such as an XML document or web page. XPath defines a kind of hierarchy of elements in the document.
You do not need to know XPath or CSS (though it might be helpful) in order to use them in actions.
The selectors are evaluated in an order as the Journey runs. If the ID does not resolve to a valid HTML element, the Journey will try other selector types according to the following order before failing:
Note: Only the Chrome engine is compatible with XPath or CSS selectors in actions. If you want the CSS or XPath to be used, make sure the Chrome engine option is selected in the Journey or audit setup.
Finding a CSS Selector or XPath
If you do not know a CSS Selector or XPath for an element, you can find it manually from the browser’s Developer Tools. The general procedure is as follows, though there may be slight differences from browser to browser:
- Right click on an element
- Choose Inspect
- Locate the element in the Elements panel of the Developer Tools
- Right click on the element’s line
- Choose Copy -> Copy Selector or Copy -> Copy XPath
- Paste the result into the ID field of an action
A CSS selector for the blog link’s anchor tag might look like this:
a[href=’/blog’
An XPath to the same blog link (above) on jpstyle.us might look like this:
Validating CSS Selectors as Input and Click Functions for Journeys
Testing in the Browser
You can test your XPath or CSS selector in Chrome’s JavaScript console by wrapping it in a statement, like this:
For example, use the following to select the Blog link at http://jpstyle.us. The red text is the selector.
Additional Resources
More details about XPaths and CSS selectors is beyond the scope of this document, but there are several sites on the web that teach about them or have reference materials, including these from W3Schools.com: XPath Introduction and CSS Selectors Reference.
Thanks for the feedback There was a problem submitting your feedback. Please try again later.
Last updated on March 6, 2023