I am writing integration tests for an asp.net mvc website using Selenium Webdriver. I am using C# but answers in C# or Java would be appreciated. I have attached the html table and the generated html code.
I want to click the edit link of groupname "bcde" using webdriver. To click the link, I need the id (2138) & not group name (bcde). I have tried
driver.FindElements(By.XPath("//tr[contains(td[2], 'bcde')]/td[1]").ToList()[0])
but it gives 2137, id of abcde (alphabetically first group containing find string "bcde"). I need the id 2138 of the exact matching groupname "bcde".
<table class="table">
<tr>
<th>
Group id
</th>
<th>
Group Name
</th>
<th>
</th>
</tr>
<tr>
<td>
2137
</td>
<td>
abcde
</td>
<td>
<span><a href="/Group/Edit/2137" id="lnkGroupEdit">Edit</a> | </span>
<span> <a href="/Instrument?groupID=2137" id="lnkGroupDelete">Delete</a> | </span>
</td>
</tr>
<tr>
<td>
2138
</td>
<td>
bcde
</td>
<td>
<span><a href="/Group/Edit/2138" id="lnkGroupEdit">Edit</a> | </span>
<span> <a href="/Delete?groupID=2138" id="lnkGroupDelete">Delete</a> | </span>
</td>
</tr>
<tr>
<td>
2139
</td>
<td>
a bcde f
</td>
<td>
<span><a href="/Group/Edit/2139" id="lnkGroupEdit">Edit</a> | </span>
<span> <a href="/Instrument?groupID=2139" id="lnkGroupDelete">Delete</a> | </span>
</td>
</tr>
</table>
Try this.
//tr/td[contains(.,'2137')]/..//span/a[.='Edit']
Notice the .
See my explanation here. ..
in xpath
allows you to go back and forth of the html
hierarchy easily. I used contains
because the value of the td
has whitespaces
Edit Try this. Seems like it's a wait issue
By byXpath = By.XPath("//tr/td[contains(.,'2137')]/..//span/a[.='Edit']");
new WebDriverWait(Driver,TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byXpath)).Click();
2nd Edit
Most interestingly the a
tag that you are trying to click contains respective id
. So the best solution of this problem is to use the following xpath
as per my understanding
//a[contains(@href,'2138')][.='Edit']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With