Click button inside of table using Following-Sibling PYTHON

724 views Asked by At

I have a table of 4 rows and 4 columns. There are two buttons that are on the last 2 columns: Start and Cancel. I want to press the Cancel button for the second row/ last column. The code for each row is similar... minus the service name that I am trying to start.

<table class="table">
    <tbody>
      ---this is the first row---
       <tr ng-repeat="toyService in theService" ng-class="{'text-muted':toyservice.notFound" class="ng-scope">
      --- this is the second row.. the row I am trying to start----
       <tr ng-repeat="toyService in theService" ng-class="{'text-muted':toyservice.notFound" class="ng-scope">
            <td style="text-align:center">...</td>
            <td class="ng-binding"> Toy Service 2 </td>
            <td class="ng-binding">...</td>
            <td class="toy-service-button-panel text-right">
               ----the first button (Start Button)
                <button type="submit" class="btn btn-info">...</button>
                ----the button I am trying the click (Cancel)
                <button type="submit" class="btn btn-success btn-sm"
                     <span title="Cancel Service">..</span>

Each row has the same code minus the service name:

row 1 Toy Service 1

row 2 Toy Service 2

row 3 Toy Service 3

row 4 Toy Service 4

What I tried was:

driver.find_element_by_xpath("//td[contains(text(), 'Toy Service 2')]/follow-sibling::td").find_element_by_css_selector("td[class='toy-service-button-panel.text-right']").find_element_by_css_selector("button[class='btn.btn-success.btn-sm']").click()

I get an error that says

Failed to execute 'evaluate on 'Document: The string //td[contains(text(), Toy Service 1')]/follow-sibling::td' is not a valid XPath expression.

I've tried different methods but I can not seem to click this Cancel button on row 2

1

There are 1 answers

0
alecxe On BEST ANSWER

It is not follow-sibling, it is following-sibling:

driver.find_element_by_xpath("//td[contains(text(), 'Toy Service 2')]/following-sibling::td")

But, I don't think your approach would work since the following-sibling::td would match the very next td elements after the <td class="ng-binding"> Toy Service 2 </td>, which does not contain the desired button.

Instead, I would first figure out the tr element which you want to work with:

row = driver.find_element_by_xpath("//tr[td[contains(., 'Toy Service 2')]]")

Then, I would operate inside this row:

row.find_element_by_css_selector("td.toy-service-button-panel button.btn.btn-success").click()

I've also simplified our selectors a bit, no need to check the complete class attribute values - you can check individual classes with a dot-notation.