我正在使用 Java 和 Selenium 自动执行任务。
我想根据第二列中的值是否与我的输入值匹配来设置一个复选框(位于表的第一列中)。例如,在下面的代码片段中,值“Magnus”与我的输入值匹配,因此我想设置与其关联的复选框。
<table class="cuesTableBg" width="100%" cellspacing="0" border="0" summary="Find List Table Result">
<tbody>
<tr class="cuesTableBg">
<tr class="cuesTableRowEven">
<tr class="cuesTableRowOdd">
<td align="center">
<input class="content-nogroove" type="checkbox" name="result[1].chked" value="true">
<input type="hidden" value="1c62dd7a-097a-d318-df13-75de31f54cb9" name="result[1].col[0].stringVal">
<input type="hidden" value="Magnus" name="result[1].col[1].stringVal">
</td>
<td align="left">
<a class="cuesTextLink" href="userEdit.do?key=1c62dd7a-097a-d318-df13-75de31f54cb9">Magnus</a>
</td>
<td align="left"></td>
<td align="left">Carlsen</td>
<td align="left"></td>
</tr>
<tr class="cuesTableRowEven">
</tbody>
</table>
但是我做不到。在上述情况下,以下两行即可达到目的(因为我的输入值与第二行中的值匹配):
WebElement checkbox = driver.findElement(By.xpath("//input[@type = 'checkbox' and @name = 'result[1].chked']"));
checkbox.click();
但它不能被使用,因为所需的值可能并不总是在第二行。
我尝试了以下代码块但无济于事:
List<WebElement> rows = driver.findElements(By.xpath("//table[@summary = 'Find List Table Result']//tr"));
for (WebElement row : rows) {
WebElement userID = row.findElement(By.xpath(".//td[1]"));
if(userID.getText() == "Magnus") {
WebElement checkbox = row.findElement(By.xpath(".//input[@type = 'checkbox']"));
checkbox.click();
break;
}
}
就其值(value)而言,第二列中文本的 XPath:
/html/body[@id='mainbody']/table/tbody/tr/td/div[@id='contentautoscroll']/form/table[2]/tbody/tr[3]/td[2]/a
我不知道CSS Selectors 。这会有帮助吗?
最佳答案
如果您已经知道输入值,则只需使用下面的 xpath 来选择受尊重的复选框
"//a[text(),'Magnus']/parent::td/preceding-sibling::td/input[@type='checkbox']"
更新:
"//a[text()='Magnus']/parent::td/preceding-sibling::td/input[@type='checkbox']"
关于java - 如何根据表格第二列中的值设置第一列中的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15786300/