简体   繁体   中英

Get element by cssSelector 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 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 .

您可以通过元素选择器使用它

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

Try these codes below:

1- For returning '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- For returning '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);

If you don't have to you could also use XPath selectors which are in my opinion easier to use when you have to select the nth element of something. Try this one:

For E-Mail:

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

For the password:

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

But could you also provide the full HTML page you are working with? Maybe the form is inside an iframe and therefore Selenium has problems locating the element

您需要添加.getText()方法才能获取标记内的文本。

Have you tried something like object.getAttribute("innerHTML") , literally with "innerHTML" , like this ?

I had a similar problem getting a text from a span tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM