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

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.
READ :   Handle Dynamic Html Tables Use Selenium WebDriver

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

Download “SeleniumXPathCssSelectorExample-2.zip” SeleniumXPathCssSelectorExample-2.zip – Downloaded 79 times – 2 KB

(Visited 2,070 times, 1 visits today)

Leave a Reply

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.