Get cssSelector element in Selenium (Java)

<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="dfsf@gmail.com" 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 enter a valid email address" and "Password must not be empty" using nth-child

c cssSelector

.

I tried the following 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");
    }

      

The result is NoSuchElementFound

.

+3


source to share


4 answers


You can use it with an element selector



By.cssSelector("input[name=email]")

      

+3


source


Try the following codes:

1- To return "Please provide a valid email address":

String a = driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(1)>span")).getText();
System.out.println(a);

      



2- To return "Password must not be empty":

String a = driver.findElement(By.cssSelector("form#frmlogin div.form-group:nth-child(2)>span")).getText();
System.out.println(a);

      

+1


source


If you don't need that, you can also use XPath selectors, which in my opinion are easier to use when you need to select the nth element of something. Try the following:

For E-Mail:

By.xpath("//div[@class='form-group'][1]/span")

      

For password:

By.xpath("//div[@class='form-group'][2]/span")

      

But could you also provide a complete HTML page that you are working with? Perhaps the form is inside an iframe and therefore Selenium has problems finding the element

0


source


Have you tried something like object.getAttribute("innerHTML")

, literally with help "innerHTML"

like this?

I had a similar problem getting text from span tag

-1


source







All Articles