Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium webdriver get text of adjacent column in same row by matching text from other column

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".

enter image description here

<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>
like image 728
user2330678 Avatar asked Sep 18 '25 19:09

user2330678


1 Answers

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']
like image 188
Saifur Avatar answered Sep 20 '25 10:09

Saifur