Selenium:如何通过 div 和标签从嵌套输入中获取选中的复选框?

Selenium: How can I get the checked checkbox from nested input by div and label?

Html 先挡住:

<div class="formClass" style="line-height: 18px; display: block;">

    <label id="randomId_34_30078" style="display: none; width:47%; margin-right: 5px;">
        <input type="checkbox" value="30078" disabled="">First Text
    </label>

    <label id="randomId_34_30077" style="display: none; width:47%; margin-right: 5px;">
        <input type="checkbox" value="30077" disabled="">Second Text
    </label>
    
    <label id="randomId_32_30078" style="display: inline-block; width:47%; margin-right: 5px; vertical-align: top;">
        <div style="display: inline-block; width: 10%; float: left;">

             <input type="checkbox" value="30078" disabled="" checked="">

        </div>
        <div style="display: inline-block; width: 90%; float: right;">
            First Text
        </div>
    </label>

    <label id="randomId_32_30077" style="display: inline-block; width:47%; margin-right: 5px; vertical-align: top;">
        <div style="display: inline-block; width: 10%; float: left;">
            
            <input type="checkbox" value="30077" disabled="">
        </div>
        <div style="display: inline-block; width: 90%; float: right;">
            Second Text
        </div>
    </label>

</div>

我想获取上面 HTML 部分中值为“30078”的复选框。 标签的id是随机的,也是input/checkbox的值。这是一个遗留项目。我无法修改结构。

我试过这个:

driver.findElement(By.className("formClass"))
                    .findElement(By.xpath("//label//div[contains(text(), 'First Text')]"))

但这有两个元素。

如果需要获取checkbox,需要为tag写XPATH

如果您需要为以下内容编写 xpath :

 <label id="randomId_34_30078" style="display: none; width:47%; margin-right: 5px;">
    <input type="checkbox" value="30078" disabled="">First Text
</label>

你可以使用

//div[@class="formClass"]/label/input[contains(text(),"First Text")]

虽然有两个属性为value="30078"的元素,其中只有一个可见,而另一个包含属性style="display: none;.

因此,要将 value 属性设置为 30078 的 visible/interactable 复选框,您需要引入 对于 elementToBeClickable(),您可以使用以下任一 定位器策略

  • cssSelector:

    WebElement element = new WebDriverWait(webDriver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("label[id^='randomId'] input[value='30078']")));
    
  • xpath:

    WebElement element = new WebDriverWait(webDriver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//label[starts-with(@id, 'randomId')]//input[@value='30078']")));
    

参考资料

您可以在以下位置找到一些相关讨论: