<html>
<body>
<div id="login-box" class="form-box">
<form id="frmlogin" class="form" name="frmlogin" method="post">
<div class="body">
<div class="form-group">
<input id="email" class="form-control" type="text" maxlength="50" value="[email protected]" placeholder="Email" name="email">
<span class="red">Please provide a valid email address</span>
</div>
<div class="form-group">
<input class="form-control" type="password" maxlength="15" placeholder="Password" name="password">
<span class="red">Password must not be empty</span>
</div>
</div>
</form>
</div>
</body>
</html>
I need to get "Please provide a valid email address" and "Password must not be empty" using nth-child
in cssSelector
.
I tried the below snippet:
//Case 2
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("");
String a=driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(1)>span")).getText();
System.out.println(a);
if(a.contains("valid email address"))
{
System.out.println("Login test case2 Passed");
}
else
{
System.out.println("Login test case2 Failed");
}
It results in NoSuchElementFound
.
We can locate an element by using the starting text of the element. It is quite useful if you know the starting text of the element attribute. We can use the starting character sequence of the attribute value to locate the element using CSS Selectors. Here, we have used the id attribute.
Type “css=input[type='submit']” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value. Attribute: Used to create the CSS Selector.
We can traverse both forward and backward in DOM, i.e we can move from parent to child element and also from child to the parent element with xpath. However for css, we can only traverse from parent to child and not vice-versa. In terms of performance, css is better and faster, while xpath is on a slower side.
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
You can use it by element selector
By.cssSelector("input[name=email]")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With