-3

I need to get the text of a td element with selenium. I have problem with extract text, I just receive null. I tried used list, getText() and so on. The HTML code is on the picture and element looks like you can see on the picture.

getDriver().findElement(By.xpath("//*[@id=\"standortTable\"]/tbody/tr/td[2]")).isDisplayed();
String test = getDriver().findElement(By.xpath("//*[@id=\"standortTable\"]/tbody/tr/td[2]")).getText();
System.out.println(test);

But I receive NULL, just "".

enter image description here

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    if you right click in the td element in developer tools and go Copy -> Copy XPath is the path the same is in your code above? – Anton Belev Nov 18 '21 at 13:35
  • Try with this xpath once - `//table[@id='standorteTable']/tbody/tr[1]/td[2]` – pmadhu Nov 18 '21 at 15:27
  • Screenshots of the UI are great, screenshots of code or HTML are not. Please read why [a screenshot of code/HTML is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Paste the code/HTML and properly format it instead. – JeffC Nov 18 '21 at 19:47
  • Are you sure the HTML you've posted matches the location in the DOM from the screenshot? The HTML shows a table and the Standort section of the picture doesn't look like a table. I also don't see the field label "Standortname" that should be beside the "Teststandor1" value in the field. A link to the page would be really helpful here. – JeffC Nov 18 '21 at 19:50

2 Answers2

0

I guess you are missing a wait I.e. you trying to read the element text content before it is completely rendered.
Try this:

WebDriverWait wait = new WebDriverWait(getDriver(), 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@id='standortTable']//td[@aria-colindex='2']")));
String test = getDriver().findElement(By.xpath("//table[@id='standortTable']//td[@aria-colindex='2']")).getText();
System.out.println(test);
Prophet
  • 32,350
  • 22
  • 54
  • 79
0

The element is an Angular element, so to extract the text Teststandort1 you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using xpath and getText():

    System.out.println(new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@id='standortTable']//tbody//tr[@class='ng-star-inserted']//td[@aria-colindex='2']"))).getText());
    
  • Using cssSelector and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table#standortTable tbody tr.ng-star-inserted td[aria-colindex='2']"))).getAttribute("innerHTML"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352