单击 Python Selenium 中特定行的 table 中的按钮

Click button in a table on a specific row in Python Selenium

我有一个包含 table 和几行的页面,其中一些行与其他行具有相同的文本。

如果同一行中的文本包含 [=] 中的文本“real”,我想单击按钮“删除” 13=]真实的 .

<tr id="5gf5h5gh4rthhgh1" data-id="1418753">
    <td class="website">www.123.com</td>
    <td class="user_type">real</td>
    <td class="ip_address">123.123.1.1 ()</td>
    <td class="actions">
        <div class="list-action">   
            <button class="btn default check check green markAsChecked" type="button">
                <i class="fa fa-check green markAsChecked"></i>Delete</button></div></td>
</tr>

<tr id="5gf5h5gh4g5j1gh4" data-id="1418753">
    <td class="website">www.123.com</td>
    <td class="user_type">virtual</td>
    <td class="ip_address">88.123.2.2 ()</td>
    <td class="actions">
        <div class="list-action">   
            <button class="btn default check check green markAsChecked" type="button">
                <i class="fa fa-check green markAsChecked"></i>Delete</button></div></td>
</tr>

您可以尝试以下 xpath:

//tr//td[@class="user_type" and text()="real"]//following-sibling::td//button[text()="Delete"]

要在同一行包含文本 real 时单击文本为 Delete 的元素,您必须诱导 for the element_to_be_clickable() and you can use either of the following based :

  • 使用 XPATHfollowing-sibling 以及 class 属性:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class='user_type' and text()='real']//following-sibling::td[@class='actions']//button[contains(., 'Delete')]"))).click()
    
  • 使用 XPATHfollowing-sibling 索引:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class='user_type' and text()='real']//following-sibling::td[2]//button[contains(., 'Delete')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC