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
-
What issue do you getting??Helping Hands– Helping Hands2015年02月09日 15:50:26 +00:00Commented Feb 9, 2015 at 15:50
-
What is your test code returning?Kate Paulk– Kate Paulk2015年02月10日 12:01:39 +00:00Commented Feb 10, 2015 at 12:01
-
@tester23 are you satisfied with saifur's answer?user246– user2462015年04月17日 17:22:58 +00:00Commented Apr 17, 2015 at 17:22
4 Answers 4
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')]
-
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.Peter M. - stands for Monica– Peter M. - stands for Monica2015年02月09日 15:00:52 +00:00Commented Feb 9, 2015 at 15:00
-
@PeterMasiar This is a
Web Table
you know. Soids
ornames
are always not an optionsaifur– saifur2015年02月09日 15:09:26 +00:00Commented Feb 9, 2015 at 15:09
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.
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')]"));
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
Explore related questions
See similar questions with these tags.