cooler8020002000
cooler8020002000

Reputation: 39

Finding label text when id does not exist

I am using the selenium web driver to find the label text in the below html tags:

<tr id="row" style="display: inline; padding-left: 10px; padding-right: 10px;">
<td>
<table width="776" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td align="right">&nbsp;</td>
<td>&nbsp;</td>
<td align="right">&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="92" height="25" align="left">**Label Text&nbsp**;</td>
<td width="227">
<td width="170" align="left">">**Label Text 2&nbsp**;</td>
</td>
</tr>

I used driver.findElement(By.id("row")).getText(), but it retrieves me nothing. How do I get it to print Label Text. Thanks.

Upvotes: 2

Views: 1197

Answers (4)

Petr Janeček
Petr Janeček

Reputation: 38444

My take:

List<WebElement> list;
list = driver.findElements(By.xpath("id('row')//td[string-length(text()) > 1]"));

That should get a List of <td> elements which have a text node longer than 1 char (change to 5 if &nbsp; actually counts for 5 =) ).

or maybe

list = driver.findElements(By.xpath("id('row')//td[@align='left']"));

if all the elements you want to get really have in common the align = 'left' part which can be seen in your example.

Upvotes: 0

Jude Cooray
Jude Cooray

Reputation: 19862

Use the method getText

driver.findElement(By.xpath("")).getText();

Upvotes: 0

user1307037
user1307037

Reputation: 419

driver.FindElement(By.XPath(xpath)).GetAttribute("text")

Upvotes: 0

Nashibukasan
Nashibukasan

Reputation: 2028

To access the 'Label Text' cells, you will need to search for the cells themselves and not the row that contains them. If you were using WatiN this would be the case. An alternative way of finding any element with 'Label Text' would be:

ReadOnlyCollection<IWebElement> temp = driver.FindElements(By.XPath("//td[@text='Label Text'])); 

If 'Label Text' in your example is a place holder for different text this will become tricky and you could just attempt to grab each cell within the tableRow containing the cells. However, only the first row appears to have an id. Hope this helps!

EDIT: Alternatively, a (very) hacky solution if you know exactly which cell you want and it has a unique size (like your example) you could try finding all cells and then search through their widths manually. Eg: foreach(IWebElement temp in tempCells) { if(temp.Size.Width == 170) temp.Text; }

Upvotes: 1

Related Questions