复选框元素的 Xpath 通过按值定位它在标签元素之后

Xpath for checkbox element by locating it's following label element by value

我已经为此工作了很长一段时间,但仍然没有在 Whosebug 或我自己试验 Xpath 中找到特定于我的问题的答案。我没有经验,所以如果这是一个简单的问题,我会很抱歉,但我真的很感激任何帮助。

我正在使用 Selenium 测试使用 Wicket 的 Web 应用程序。我需要 Xpath 到与相应标签相关的复选框。这是因为我需要能够输入标签上显示的值,并根据标签文本(例如“001”)找到相关的复选框,因为复选框 ID 与值不匹配。

下面的模型显示了复选框及其相应的标签;

对应的HTML如下图;

<span wicket:id="excludeDepotCheckBox" id="excludeDepotCheckBox5">

  <input name="adminPreferenceSection:excludeDepotCheckBox" type="checkbox" value="0" id="excludeDepotCheckBox5-adminPreferenceSection:excludeDepotCheckBox_0">
  <label for="excludeDepotCheckBox5-adminPreferenceSection:excludeDepotCheckBox_0">001</label>

  <br>

<input name="adminPreferenceSection:excludeDepotCheckBox" type="checkbox" value="1" id="excludeDepotCheckBox5-adminPreferenceSection:excludeDepotCheckBox_1">
  <label for="excludeDepotCheckBox5-adminPreferenceSection:excludeDepotCheckBox_1">009</label>

  <br>

</span>

我还面临的另一个问题是 Xpath 必须包含这样一个事实,即它位于 html 中显示的范围内,因为页面上还有其他 3 组复选框具有相同的值,因此它必须具体到每个跨度,例如:

id="excludeDepotCheckBox5"

我尝试了以下 Xpaths 都无济于事;

//span[@id='excludeDepotCheckBox5' and contains(., '009')]"

"//*[@id='excludeDepotCheckBox5' and ./label/text()='009']/preceding-sibling::*[@name='adminPreferenceSection:excludeDepotCheckBox']

//*[@id='excludeDepotCheckBox5' and ./label/text()='009']/preceding-sibling::input[1]"

如果这是一个简单的 syntax/understanding 问题,我再次表示歉意,但我真的很感激任何帮助。

您可以使用以下 xpaths:

1- 对于 选中与标签“001”相关的复选框:

//span[@id='excludeDepotCheckBox5']/label[.='001']/preceding-sibling::input[1]

2- 对于 选中与标签“009”相关的复选框:

//span[@id='excludeDepotCheckBox5']/label[.='009']/preceding-sibling::input[1]

注意:它将检查 'input' 元素,它是 label 元素的第一个在前的兄弟元素,在 span 下具有确切的 innerHTML/text 作为 '001' 或 '009' id='excludeDepotCheckBox5'.

的元素

//*[@id='excludeDepotCheckBox5']/label[contains(text(),'001')]//preceding-sibling::input[1]

由于"preceding-sibling"非常容易出错(只要HTML结构稍有变化就会崩溃),这里有一个更稳定的变体(为了易读性包装):

//span[@id = 'excludeDepotCheckBox5']//input[
    @id = //span[@id = 'excludeDepotCheckBox5']//label[normalize-space() = '001']/@for
]