Category Menu


Interview Questions Category Menu

Interview Questions

Cheat Sheet Category Menu

Cheat Sheets

How to enter value in a text box for which no locators are available

Posted on

Scenario : You have given a form in which will have a username field, password field and submit button. Each of these elements will not have any locators like ID, Class or any attributes other than Tag. How will you identify these elements and set values in this form and click on Submit button.
The HTML code will look like the following
<div>First Name</div>
<input type = "text"/>
<div>Last Name</div>
<input type = "text"/>
<input type = "submit"/>
The actual rendering of the page will look like the following:-
First Name
Last Name
In the above form there is no ID or Class given to any of the element. Also the type attribute is common for tow text box hence any change in the order of the element in future will again make our script go wrong. Hence we cannot use any locators other than XPath. We can use tag here with index but not the ideal one if the application change is expected. The best option for this will be relative XPath, though you can use various flavors of XPath. Lets take a look at the XPath that we will be using for this.

For First Name : //div/div[text()='First Name']/following-sibling::input[1]
For Last Name : //div/div[text()='Last Name']/following-sibling::input[1]
For Submit Button : //input[@type='submit']
First of all lets understand why we are using such a long and complex XPath.

In case of First Name and Last Name, there is no other attribute which will uniquely identify the element. Though there is type attribute but it is common in both the element. Considering the risk of the change in order of two element, we have to come up with something which will work even if the order of First Name and Last Name interchange in future. Hence the label plays an important role here to uniquely identify these elements. Here we are finding the label first and then locating its following first sibling. This will solve our problem and will even work if the order changes.
In case of Submit button, if you look at the tag name for all three element we have the same name but what it makes the submit button stand out is we have type attribute which will uniquely identify the element in he given form, unless there are multiple buttons. Hence we can use small XPath with just type attribute.
Let's see how it looks when we put everything together in the code.
WebDriver wd = new ChromeDriver();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
wd.findElement(By.xpath("//div/div[text()='First Name']/following-sibling::input[1]")).sendKeys("MyFirstName")
wd.findElement(By.xpath("//div/div[text()='Last Name']/following-sibling::input[1]")).sendKeys("MyLastName")
In this way we can easily identify the elements even if there is no unique identifier available. This code will work even if the order of the elements changes.