3

I used following code:

driver.getPageSource().contains("My value in text box");

This will let me know, element present in dom or not.

Now, i need to know , value containing text-box "My value in text box". What is id of this text box.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
deepak mishra
  • 310
  • 2
  • 13
  • Possible duplicate of [How do I find an element that contains specific text in Selenium Webdriver (Python)?](https://stackoverflow.com/questions/12323403/how-do-i-find-an-element-that-contains-specific-text-in-selenium-webdriver-pyth) – Sers Mar 01 '19 at 09:46

1 Answers1

3

To extract the id of a dom element you don't need to invoke getPageSource(). You can simply use the getAttribute() method as follows:

String elementID = driver.findElement(By.xpath("//*[contains(text(),'My value in text box')]")).getAttribute("id");
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Just a caveat: sometimes the text is contained in a label, not an input element. However, it is common practice for that label to have a "for" attribute which does contain the ID for the input element. I would check the tag of the returned xpath first to see if it's a label and then get the actual input via ID, otherwise it would be fairly safe to assume it's what you were looking for. – Bill Hileman Mar 01 '19 at 21:05