Reputation: 768
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
Reputation: 193138
You haven't mentioned any Selenium Language Binding Art so I will be using Java for the example.
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");
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 :
<span>
tag) will make your Testcases to Fail.<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.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
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
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