问题描述
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是随机的,也是输入/复选框的值。这是一个遗留项目。我无法修改结构。
我尝试过:
driver.findElement(By.className("formClass"))
.findElement(By.xpath("//label//div[contains(text(),'First Text')]"))
但这有两个元素。
解决方法
如果需要选中此复选框,则需要为代码编写XPATH。
如果您需要为以下内容编写xpath:
allow_any_instance_of
您可以使用
<label id="randomId_34_30078" style="display: none; width:47%; margin-right: 5px;">
<input type="checkbox" value="30078" disabled="">First Text
</label>
,
尽管有两个元素具有属性value="30078"
,但其中只有一个可见,而另一个元素包含属性 style="display: none;
。
因此,要获得将 value 属性设置为 30078 的可见/可交互复选框,您需要为elementToBeClickable()
引入WebDriverWait,并且可以使用以下定位器策略之一:
-
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']")));
参考文献
您可以在以下位置找到一些相关的讨论