Aabesh Karmacharya
Aabesh Karmacharya

Reputation: 768

How to find Label of a input field

Looking for a generic way to find text before an input field to know what to fill in the field. Using xpath, css selector or any other way possible.

<div>
    <span>Full Name</span>
    <input name="xddadN">
</div>
<div>
    <span>Email</span>
    <input name="xedadN">
</div>

Or

<div>
    <div><label>Full Name</label></div>
    <div><input name="xddadN"></div>
    <div><label>Email</label></div>
    <div><input name="xedadN"></
</div>

Or

<div>
    <label>Full Name<br>
    <span><input name="xddadN"></span>
    </label>
</div>
<div>
    <label>Full Name<br>
    <span><input name="xddadN"></span>
    </label>
</div>

Upvotes: 0

Views: 864

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193138

You haven't mentioned any Selenium Language Binding Art so I will be using Java for the example.

First the Answer

Yes, you can use a generic way to find text before an input field as follows :

  • As per the HTML :

    <div>
        <span>Full Name</span>
        <input name="xddadN">
    </div>
    <div>
        <span>Email</span>
        <input name="xedadN">
    </div>
    
  • To retrieve the text Full Name from the <span> tag with respect to the <input> tag you can use :

    String myText = driver.findElement(By.xpath("//input[@name='xddadN']//preceding::*[1]")).getAttribute("innerHTML");
    

Now the Pitfall

Without any visibility to your usecase in my opinion the generic way would be a pitfall which will induce much chaos and uncertanity for the following reasons :

  • As per the xpath we are straightway jumping into the previous element, a small change in the HTML DOM (e.g. inclusion of a <span> tag) will make your Testcases to Fail.
  • In general, while constructing a Locator Strategy through css-selectors or xpath it will be benificial to include the <tagName> to optimize the element search process. If <tagName> are not included your Tests will require more time to locate the elements and perform action on them. In this process you are compromising some of the advantages of Test Automation.

Conclusion

Hence as a conclusion as per the Best Practices always include the <tagName> while constructing a Locator Strategy through css-selectors or xpath.

Upvotes: 0

Andersson
Andersson

Reputation: 52665

You can try below XPath expression to get preceding text node:

//input/preceding::*[1]

or more specific for Full Name

//input[@name="xddadN"]/preceding::*[1]

and Email:

//input[@name="xedadN"]/preceding::*[1]

Upvotes: 2

cruisepandey
cruisepandey

Reputation: 29362

For full name use this Xpath : //input[@name='xddadN']/preceding-sibling::span

code :

String fullName = driver.findElement(By.Xpath(//input[@name='xddadN']/preceding-sibling::span)).getText();  

String Email = driver.findElement(By.Xpath(//input[@name='xedadN']/preceding-sibling::span)).getText();  

Upvotes: 0

Related Questions