34

How do I get the first table (table1) using xpath for Webdriver?

<span id="dynamically generated id" data-id="table1">
  <table>
  ...
  </table>
</span>

<span id="dynamically generated id" data-id="table2">
  <table>
  ...
  </table>
</span>

I am able to get all data-id elements but I want to filter within it for text table1 to get the exact element.

This did not work!

driver.findElement(By.xpath("//@*[starts-with(name(),'data-id') [contains(text(),'table1')]]")); 
Bala
  • 11,068
  • 19
  • 67
  • 120

4 Answers4

36

You get the table like this:

//span[@data-id='table1']/table

Select the data-id attribute and get the child element of name table.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
29

Answering my own question...This appears to get the exact element.

driver.findElement(By.xpath("//*[@data-id='table1']"))
Nickolaus
  • 4,785
  • 4
  • 38
  • 60
Bala
  • 11,068
  • 19
  • 67
  • 120
  • this may work but generally for automation testing on projects undergoing development it may not be good practice since if any changes are made to the dom on that specific page your xpath will most likely change and you'll have to re-write the test cases – d0rf47 Jan 18 '21 at 23:47
3

I think you can also use the cssSelector

driver.findElement(By.cssSelector("[data-id='table1']"));
Adam Bilinski
  • 1,188
  • 1
  • 18
  • 28
2

Try (built this be combining xpath: find a node that has a given attribute whose value contains a string and Getting attribute using XPath)

driver.findElement(By.xpath("//*[contains(@data-id, 'table1')]/@data-id"));
Community
  • 1
  • 1
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93