Java Selenium webdriver - 单击基于表值的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19220666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium webdriver - clicking on checkbox based on table value
提问by user2853922
i am currently working java/selenium webdriver automation. However i am stuck at this particular part which i am unable to make the webdriver click on the checkbox based on a value.
我目前正在工作 java/selenium webdriver 自动化。然而,我被困在这个特定的部分,我无法让 webdriver 基于一个值点击复选框。
driver.findElement(By.xpath("//input[@class='chkPopupCod']/following::td[contains(text(),'BBB')]")).click();
driver.findElement(By.xpath("//input[@class='chkPopupCod']/following::td[contains(text(),'BBB')]")).click();
It works when i did not use the Axes part of xpath, however it can only select the first checkbox
当我没有使用 xpath 的 Axes 部分时它可以工作,但是它只能选择第一个复选框
Below is a snippet of the html
下面是html的片段
<tr class="even">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox">codData=Object { id=101914, codId=101906, label="AAA", more...}
</td>
<td class="" align="left">AAA</td>
</tr>
<tr class="odd">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox" style="background-color: rgb(255, 255, 255);">codData=Object { id=101918, codId=101907, label="BBB", more...}
</td>
<td class="" align="left" style="background-color: transparent;">BBB</td>
</tr>
<tr class="even">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox">codData=Object { id=101922, codId=101908, label="CCC", more...}
</td>
<td class="" align="left">CCC</td>
</tr>
采纳答案by Arran
You have the right idea in your XPath. Just flip it around:
您在 XPath 中有正确的想法。只需翻转它:
//td[contains(text(),'BBB')]/preceding::td/input[@class='chkPopupCod']
As in, get that element that has the text inside it first. Make your way through the tree afterthat.
如,获得具有里面的文本元素第一。在那之后穿过树。
回答by Tedesco
When working with tables I always like to first identify which table row I am working on. For this, I have a method to return me the table row and then from there I start looking for the element I wish to use.
在处理表格时,我总是喜欢首先确定我正在处理的表格行。为此,我有一种方法可以返回表格行,然后从那里开始寻找我希望使用的元素。
Example: Method to get the parent table row -
示例:获取父表行的方法 -
public void IWebElement GetParentTableRow(IWebElement element)
{
while (!element.TagName.ToLower().Equals("tr"))
{
try
{
element = element.FindElement(By.XPath("..")); //Returns the parent
}
catch
{
return null;
}
}
return element;
}
Usage -
用法 -
public void Test()
{
IWebElement tableRow = GetParentTableRow(driver.FindElement(By.XPath("//td[contains(text(),'BBB')]"));
tableRow.FindElement(By.ClassName("chkPopupCod")).Click();
}
Hope it helps. :)
希望能帮助到你。:)