[英]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.