Selenium XPath Css Selector Example

In selenium, you can use id, name as locator to find Web Elements accurately. But in some cases, id is generated dynamically and name is also not provided. So XPath and Css selector is the most efficient way to locate web elements in such scenario. We will show you examples of using XPath and Css selector to find web elements in this article.

This example will use below html file content.

<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>

xpath css selector example page

There are following web elements in the html form.

  1. Username and password has id and name with different value.
  2. Two email input text box has same name different value. And the email label is wrapped by html span tag.
  3. Submit button has id, value and style attribute.
  4. Reset button has id , value and class attribute.
  5. Two links for “Forget Password” and “Register”.

Locate Web Element By XPath Example

  1. Use id : //*[@id="userName"].
  2. Use name : //input[@name="passwd"].
    If there has two input text box with same name “email” as the example code, we can use //*[@name='email'][1], the index start from 1.
  3. Use name and value : //input[@name='email'][@value='[email protected]'].
  4. Use css style value : //input[@name='email'][@style='background-color: red'].
  5. Use complete match text : //span[.='Email1'].
  6. Use partial match text : //*[contains(text(),'Email')].
  7. Case insensitive xpath use translate() : //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'EMaIl')]
  8. Use html a tag href :  //a[@href='forgetPassword.html'].
  9. Click here to learn more xpath functions.

Locale Web Element By Css Example

Css is 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 web element’s css attribute to locate a web element in the web page. Css selector is more simpler and faster than XPath especially in Internet Explorer.

  1. Syntax : tagName[attributename=attributeValue].
  2. Dot(.) is used to refer to css class : input.btnBackground.btnFont.
  3. Hash(#) is used to refer to id : input#userName.
  4. Use id : input[id=userName].
  5. Use name : input[name=passwd].
  6. Get web element list with same name element : input[name=email].
  7. Use name and value : input[name=email][value='[email protected]'].
  8. Use css style : input[name=email][style='background-color: red'].
  9. Use html a tag href : a[href='forgetPassword.html'].
  10. ‘^’ means start of the string : input[name^='em'].
  11. ‘$’ means the end of the string : input[name$='il'].
  12. ‘*’ means contain the string : input[name*='ai'].
  13. Use child node selector : form>input[name*='ai'].
  14. Use “+” to locate two or more adjacent web element : input#submitBtn+input[id='resetBtn'].

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.");

[download id=”1928″]

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.