在我正在测试的应用程序页面的用户界面上,有一个如上图所示的表格。表格的第 5 列,标题“组”下的每一行都有一个下拉列表。所有下拉菜单都具有相同的 ID“RID”。
检查“Apple”仓库元素:
<div id="sdiv" …>
<table id="table10987654321" …>
<tbody>
<tr …>
<td …>
<a …>
<span …>
APPLE</span>
</a>
</td>
…
检查与“Apple”仓库同一行的组下拉列表:
<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;
}
}
}
关于java - 如何循环遍历表以在第 1 列中找到匹配的字符串,然后使用 Selenium WebDriver Java 在另一列的同一行中选择下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188576/