使用 Following-Sibling PYTHON 单击 table 内的按钮

Click button inside of table using Following-Sibling PYTHON

我有一个 4 行 4 列的 table。最后两列有两个按钮:开始取消。我想按第二行/最后一列的取消按钮。每行的代码都相似...减去我尝试启动的服务名称。

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

每一行都有相同的代码减去服务名称:

第 1 行 玩具服务 1

第 2 行 玩具服务 2

第 3 行 玩具服务 3

第 4 行 玩具服务 4

我试过的是:

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()

我收到一个错误

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

我尝试了不同的方法,但我似乎无法点击第 2 行的取消按钮

不是follow-sibling,是following-sibling:

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

但是,我认为您的方法行不通,因为 following-sibling::td 会匹配 <td class="ng-binding"> Toy Service 2 </td> 之后的下一个 td 元素,其中不包含所需的按钮。

相反,我会先找出您要使用的 tr 元素:

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

那我就在这一行里面操作:

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

我还稍微简化了我们的选择器,无需检查完整的 class 属性值 - 您可以使用点符号检查单个 类。