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>
    <style>
    .btnBackground
    {
      	background-color : red;
    }
    
    .btnFont
    {
      	font-size : 20px;
    }
    </style>
    </head>
    <body>
    <form>
    UserName : <input type=text id="userName" name="userName" value="Jerry" /><br/>
    Password : <input type=password id="passwd" value="dev2qa.com" 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>
    </form>
    </body>
  2. Below is the above Html web page in a web browser.
    xpath-css-selector-example-page
  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.

  1. TestXPathCssSelector.java
    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");
    		
    		List<By> locatorList = new ArrayList<By>();
    		
    		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)
    	{
    		List<WebElement> eleList = 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.");
    		}
    	}
    }

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.