[英]Selenium Webdriver Java: How to click on a particular cell in table using row and column numbers
[英]How to loop through table to find a string match in column 1, then select a dropdown on the same row in another column using Selenium WebDriver Java?
在我正在测试的应用程序页面的 UI 上,有一个类似于上图的表格。 表格的第 5 列,标题“组”下的每一行都有一个下拉列表。 所有下拉菜单都具有相同的 ID 'RID'。
检查“Apple”仓库元素:
<div id="sdiv" …>
<table id="table10987654321" …>
<tbody>
<tr …>
<td …>
<a …>
<span …>
APPLE</span>
</a>
</td>
…
检查与“Apple”仓库同一行的 Group 下拉列表:
<div id="sdiv" …>
<table id="table10987654321" …>
<tbody>
<tr …>
<td …>
<td …>
<td …>
<td …>
<td …>
<span …>
<select id="RIDs" …>…</select>
</span>
…
为了定位这个表中的所有行,我写道:
@FindAll(@FindBy(css="div[id='sdiv']>table[id^='table'] tr"))
List<WebElement> tableRows;
为了找到组下拉菜单,我写道:
@FindAll(@FindBy(css="div[id='sdiv']>table[id^='table'] td:nth-child(5) select[id='RIDs']"))
WebElement dropdownGroup;
使用 PageFactory.initElements 初始化元素后,现在我想逐行遍历表的第一列,以找到我要查找的仓库,在本例中为“BLUEBERRY”仓库。 如果仓库是“BLUEBERRY”,则从与“BLUEBERRY”仓库相同行的第 5 列的下拉列表中选择一个组。
public void selectGroup (String string) {
for (WebElement row : tableRows) {
String warehouseCell = row.findElement(By.cssSelector("td:nth-child(1)).getText());
If (warehosueCell.equals("BLUEBERRY")) {
Select group = new Select(this.dropdownGroup);
group.selectByVisibleText(string);
}
Else {
continue;
}
}
}
然后,在另一个类中,我调用上述方法:
String string = "NEWGROUP";
GroupPage page = new GroupPage(driver, WAIT_TIMEOUT);
page.selectGroup(string);
当我运行它时,它选择了“APPLE”仓库行中的下拉菜单,而不是“BLUEBERRY”仓库行。
如何更改代码以便它选择与我要查找的仓库位于同一行的下拉列表?
我想过用for循环加上索引,但是表的大小可以改变,并且可以添加新的仓库,所以我不知道什么时候结束循环。
终于解决了。
@FindAll(@FindBy(css="div[id='sdiv']>table[id^='table'] td:nth-child(5) select[id='RIDs']"))
List<WebElement> dropdownGroups;
public void selectGroup (String string) {
int i = 0;
for (WebElement row : tableRows) {
String warehouseCell = row.findElement(By.cssSelector("td:nth-child(1)).getText());
if (warehosueCell.equals("BLUEBERRY")) {
Select group = new Select(this.dropdownGroups.get(i));
group.selectByVisibleText(string);
System.out.println("Group " + group.getFirstSelectedOption().getText() + " is selected.");
}
else {
i++;
continue;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.