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.

  1. TestXPathCssSelector.html
    <title>Test XPath Css Selector Example</title>
      	background-color : red;
      	font-size : 20px;
    UserName : <input type=text id="userName" name="userName" value="Jerry" /><br/>
    Password : <input type=password id="passwd" value="" name="passwd" /><br/>
    <span>Email1</span> : <input type=text name="email" value="[email protected]"/><br/>
    <span>Email2</span> : <input type=text name="email" value="[email protected]" style="background-color: red"/><br/>
    <input type="submit" id="submitBtn" value="Submit" style="background-color: green"/>
    <input type="reset" id="resetBtn" value="Reset" class="btnBackground btnFont"/><br/>
    <a href="forgetPassword.html">Forget Password</a> <a href="regist.html">Register</a>
  2. Below is the above Html web page in a web browser.
  3. There are the following web elements in the above Html form.
  4. Username and password have id and name with different values.
  5. Two email input text box has the same name but different value. And the email label is wrapped by an Html span tag.
  6. The Submit button has id, value, and style attributes.
  7. The Reset button has id, value, and class attributes.
  8. Two links for “Forget Password” and “Register“.

2. Locate Web Element By XPath Example.

  1. By id : //*[@id="userName"].
  2. 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.
  3. By name and value : //input[@name='email'][@value='[email protected]'].
  4. By CSS style value : //input[@name='email'][@style='background-color: red'].
  5. By complete match text : //span[.='Email1'].
  6. By partial match text : //*[contains(text(),'Email')].
  7. Case insensitive xpath use translate(): //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'EMaIl')]
  8. By Html a tag href attribute:  //a[@href='forgetPassword.html'].
  9. Click here to learn more about XPath functions.

3. Locale Web Element By CSS Example.

  1. CSS is the abbreviation of “Cascading Style Sheet“. It is used in Html to make web element’s layout and style beautifully.
  2. CSS selector is a path pattern that can use a web element’s CSS attribute to locate a web element in the web page.
  3. CSS selector is simpler and faster than XPath, especially in Internet Explorer.
  4. Syntax : tagName[attributename=attributeValue].
  5. A dot (.) is used to refer to CSS class : input.btnBackground.btnFont.
  6. Hash(#) is used to refer to id : input#userName.
  7. By id : input[id=userName].
  8. By name : input[name=passwd].
  9. Get web element list with same name element : input[name=email].
  10. By name and value : input[name=email][value='[email protected]'].
  11. By CSS style : input[name=email][style='background-color: red'].
  12. By Html a tag href attribute: a[href='forgetPassword.html'].
  13. ‘^’ means the start of the string : input[name^='em'].
  14. ‘$’ means the end of the string : input[name$='il'].
  15. ‘*’ means contain the string : input[name*='ai'].
  16. Use child node selector : form>input[name*='ai'].
  17. 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();
    		List<By> locatorList = new ArrayList<By>();
    		By byUserNameId = By.xpath("//input[@id='userName']");
    		By byPasswordName = By.xpath("//input[@name='passwd']");
    		By byEmail1 = By.xpath("//*[@name='email'][1]");
    		By byEmailNameAndValue = By.xpath("//input[@name='email'][@value='[email protected]']");
    		By byEmailNameAndStyle = By.xpath("//input[@name='email'][@style='background-color: red']");
    		By byTextComplete = By.xpath("//span[.='Email1']");
    		By byTextPartial = By.xpath("//*[contains(text(),'Email')]");
    		By byForgetPasswordHref = By.xpath("//a[@href='forgetPassword.html']");
    		//Below are css selector example. 
    		By byCssResetClass = By.cssSelector("input.btnBackground.btnFont");
    		By byCssUserNameHashId = By.cssSelector("input#userName");
    		By byCssUserNameId = By.cssSelector("input[id=userName]");
    		By byCssPasswordName = By.cssSelector("input[name=passwd]");
    		By byCssEmail = By.cssSelector("input[name=email]");
    		By byCssEmailNameAndValue = By.cssSelector("input[name=email][value='[email protected]']");
    		By byCssEmailNameAndStyle = By.cssSelector("input[name=email][style='background-color: red']");
    		By byCssForgetPasswordHref = By.cssSelector("a[href='forgetPassword.html']");
    		By byCssEmailStartStr = By.cssSelector("input[name^='em']");
    		By byCssEmailEndStr = By.cssSelector("input[name$='il']");
    		By byCssEmailContainStr = By.cssSelector("input[name*='ai']");
    		By byCssEmailUseChildSelector = By.cssSelector("form>input[name*='ai']");
    		By byCssEmailUseaAjacentlector = By.cssSelector("input#submitBtn+input[id='resetBtn']");
    		for(By locator : locatorList)
    			TestXPathCssSelector.findElement(driver, locator);
    	private static void findElement(WebDriver driver, By locator)
    		List<WebElement> eleList = driver.findElements(locator);
    		int size = eleList.size();
    			System.out.println("There has " + size +" web element located by " + locator.toString() + " exist.");
    			System.out.println("Web element located by " + locator.toString() + " do not exist.");

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.