Select 基于 Selenium 中另一个行元素的行元素

Select a row element based on another row element in Selenium

我想 select 基于 Selenium 行中另一个元素的复选框。例如:如何select Cricket 对应的复选框?

<body>
    <table id="MyTable">
        <tbody>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>Football</td>
            </tr>
            <tr> 
                <td>
                    <input type="checkbox" />
                </td>
                <td>Cricket</td>
            </tr>
        </tbody>
    </table>
</body>

尝试以下 xpath:

driver.findElement(By.xpath("//table[@id='MyTable']//tr[contains(., 'Cricket')]//input[@type='checkbox']")).click();

看到复选框一般都是input标签,如果你想select那个使用Cricket关键字,你可以使用下面的xpath

//td[text()='Cricket']/preceding-sibling::td/input

代码中:-

driver.findElement(By.xpath("//td[text()='Cricket']/preceding-sibling::td/input")).click();

您也可以尝试显式等待:

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[text()='Cricket']/preceding-sibling::td/input"))).click();