How to locate element in selenium which has no unique identifier? [closed] How to locate element in selenium which has no unique identifier? [closed] selenium selenium

How to locate element in selenium which has no unique identifier? [closed]


Interview questions are always a challenge, and typically are trying to illicit a response (positive or negative) from the interviewee, that typically has little to do with the subject of the question so that they can gain a sense of your level of understanding or personality.

Depending on the interviewer, they might have been looking to see if you were well rounded in programming. I don't know what position you were applying. Assuming Selenium doesn't have any 'magic' method to find said element, perhaps the interviewer wanted to know if you could write, or understand parsing web-code programmatically.

Perhaps they were looking for you to quantify the element programmatically as to find it based on a parametric search.

Both of these concepts would show understanding of programming fundamentals to the interviewer without ever talking about specific code.


Well, there are so many different techniques to locate elements in the HTML. It's too broad to answer exactly, so, if I were you, I would just list the possible techniques with multiple examples. XPath expressions and CSS selectors are there to the rescue.

Tag names, id, name, class or any other data-related attributes are usually a good and reliable choice to locate elements. If none of these is present, it would depend on where the element is located, what parents, siblings, ancestors etc does it have and how unique the element text, corresponding label (if any), parents are - too many variables in action.


For instance, imagine you have the following HTML:

<span>    <label>Category:</label>    <b>Desired text</b></span>

The desired b tag here itself does not have id or name, but it's easy to see that we can probably rely on its preceding sibling and use this XPath expression:

//label[. = "Category:"]/following-sibling::*

Sometimes we know that the desired element is at a specific position in an element. For example:

<tr>    <td>text1</td>    <td>Desired text</td>    <td>text3</td></tr>

In this case, we can simply get the second td from the tr:

//tr/td[2]

Sometimes, there is something in the "text" of an element:

<div>The quick brown fox jumps over the lazy dog</div>

Let's say we know that "fox" is there:

//div[contains(., "fox")]

And so on.