1

I am a beginner in learning Selenium WebDriver and XPath. I am trying to get the "<td>" Element of the Nested Table which Contains string '7-8-9.' Following is the HTML page code:

 <!DOCTYPE html>
    <head>
    <title>Sample</title>
    </head>
    <body>
    <table border = "2">
    <tbody>
    <tr>
    <td>one</td>
    <td>two</td>
    </tr>
    <tr>
    <td>three</td>
    <td>
    <table border = 1">
    <tbody>
    <tr>
    <td>1-2-3</td>
    <td>4-5-6</td>
    </tr>
    <tr>
    <td>7-8-9</td>
    <td>10-11-12</td>
    </tr>
    </tbody>
    </table>
    </td>
    </tr>
    </tbody>
    </table>
    </body>
    </html>

this the test code :

WebElement  cell3 =  driver.findElement(By.xpath("//table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[contains(text() , '1-2-3'))]"));

    System.out.println(cell3.getText());

Please help! thanks

3
  • What issue do you getting?? Feb 9, 2015 at 15:50
  • What is your test code returning?
    – Kate Paulk
    Feb 10, 2015 at 12:01
  • @tester23 are you satisfied with saifur's answer?
    – user246
    Apr 17, 2015 at 17:22

4 Answers 4

3

First of all, you don't want the xpath to do a lot of works. So, be little bit more considerate when you the write xpath You don't need to walk down the whole hierarchy to find the element with xpath. Relative xpath would be enough for selenium. Read this

//tbody//td[contains(text(),'1-2-3')]
2
  • or even better, try not use xpath, and use IDs or names. Faster and less brittle. Ask your developers to add ID to any element. Feb 9, 2015 at 15:00
  • @PeterMasiar This is a Web Table you know. So ids or names are always not an option
    – saifur
    Feb 9, 2015 at 15:09
1

For a quick and dirty method that will be fragile and perform poorly, but will allow you to get your test working, open the page in Firefox, open the development tools, find the element in the source viewer, right click, and there should be an option to create an XPath query.

Just noticed the "contains" in the question, if that's important then ignore this answer.

1

I will suggest to use xpath only if you don't have

  • id
  • classname
  • tagname

Use contains in xpath:

  • For Android:

     driver.findElement(By.xpath("//label[contains(@id,'dv-textbox-label-SubList')]");
    
  • For iOS:

    iosDriver.findElement(By.xpath("//UIAStaticText[contains(@name,'MOBDishwasher')]"));
    
0

xpath:

//td[contains(text(),'1-2-3')]

css:

td:contains('1-2-3')

Better would be an attribute (id, class, name etc.) in the element and then for example:

xpath:

//td[@id='123-value']

or css:

td#123-value

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.