2

I have a input text box having id property and the HTML for it as shown below

username:<input type="text" id="1234"><br> 

Id property is dynamically changing. when the page loads next time.

Username:<input type="text" id="5678"><br> 

and the value continuously changing.

how to write the XPath for the above scenario.

Here we have only one ID property no other properties are available. I know we can use contains,starts-with or write absolute XPath helps in other cases.

Please help me on this.

  • 2
    Share your HTML code please. With parents. – Sagar007 May 26 '17 at 13:08
  • Will CSS locators work? Can you ask developers to add a name? – Peter M. - stands for Monica May 26 '17 at 14:07
  • 1
    Seeing the HTML code would help tremendously, as Sagar007 mentioned above, but barring that, this might work (untested): //*[contains(text(),'Username:')]/input – Bill Hileman May 26 '17 at 15:01
1

In such case I talk to a developer to introduce a fixed way to locate an element, e.g., by name attribute:

Username: <input type="text" id="5678" name="username"><br> 
  • or appending the random part of an id to a fixed one like userinput+5678. No need to introduce an entirely new tag. – Leon Jul 5 '17 at 7:50
  • @Leon. New tag doesn't cost much and using new tag will make locators clear, e.g. By.name("username"). – dzieciou Jul 5 '17 at 8:09
  • Of course, didnt say it cost something but no need to clutter up code there either. The same line that introduces the random value could be made to include a fixed part as well, no need for new lines of code. – Leon Jul 5 '17 at 10:15
1

Xpath provide following-sibling functionality with text :

Solution :

First we identify text element and then find following sibling.

Try this xpath :

//*[contains(.,'Username')]//following-sibling::input

Note : Here change initial * with parent of your input element like div or form.

0

You can try this:

driver.findElement(By.xpath("//input[text()='Username']"));
0

How I handle dynamic IDs:

  1. Inspect the element using Chrome's DevTools
  2. Edit the element and remove the id="..." attribute
  3. Right-click the element
  4. Select "Copy" > "Copy selector" (or you could do XPath if you really want)

You now have a selector that doesn't use the ID attribute, but most likely it's DOM position. Something like "body > div:nth-child(1) > input" instead of "#1234".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.