Reputation: 96544
Given
<table>
<tr>
<td>service1</td>
</tr>
<tr>
<td>service2</td>
</tr>
<tr>
<td>service3</td>
</tr>
<tr>
<td>blip</td>
</tr>
</table>
How can I select the last 'service-n' row when I don't know what n will be?
I have tried adding [last()]
but it didn't work.
I have:
//table//tr//td[contains(text(),'service')]
but it selects the 1st row and I want the last one.
I can't use tr[3]
because in reality the number of 'service-n' rows is dynamic and changes a lot.
Upvotes: 13
Views: 38508
Reputation: 1
(//div[contains(@id , "b" )])[last()]
For Example :-
if //div[@id = "abc"]
is giving 10
elements ,
We want to select 4th element we have to give ,
(//div[@id = "abc"])[4]
Similarly for last element
(//div[@id = "abc"])[last()]
Format
(Xpath)[last()]
Upvotes: 0
Reputation: 1
(//div[@id='name'])[last()]
By using we can get the last element of the relevant filed.
//div[@id='name'][last()]
Multiple elements in last
Upvotes: 0
Reputation: 446
<table id="table1">
<tbody>
<tr id="tr1">
<td id="td1"></td>
<td id="td2"></td>
<tr>
<tr id="tr2">
<td id="td3"></td>
<td id="td4"></td>
<tr>
<tbody>
</table>
Then to target last td of last tr we can have xpath as:xpath="//table[@id='table1']//tr[last()]//td[last()]";
Upvotes: 1
Reputation: 19
List<WebElement> allElement=fd.findElements(By.xpath("//table//td[contains(.,'service')]");
int count=allElement.size();
allElement.get(count-1).click();
Upvotes: 1
Reputation: 1251
try with cssSelector, this way.
By.cssSelector("table tr:last-child td")
Upvotes: 2
Reputation: 96544
The answer was exactly where I put the [last()] and I had it in the wrong place
It goes here:
//div[@id='content']//table//tr[last()]//td[contains(text(),'service')][last()]/following-sibling::td[2]
Not here:
//div[@id='content']//table//tr[last()]//td[contains(text(),'service')]/following-sibling::td[2][last()]
Upvotes: 17