基于我之前的 qu-如何使用 selenium java 从下拉列表中对每个值执行一些操作?



现在我想从下拉列表中选择第一个值,然后对其执行一些操作,然后我想从同一下拉列表中选择第二个值并对其执行相同的操作。 这是我的代码:

WebElement bldgs=Fn_GetWebElement(CreateSSIObject.getProperty("Bldgselect"));
Select  Bldg_select=new Select(bldgs);
List<WebElement> dropdownvalues = Bldg_select.getOptions();
int count=dropdownvalues.size();
System.out.println("Total number of values are :"+count);
for(int i=1;i<count;i++) {
if(dropdownvalues.get(i).isEnabled()) {
Bldg_select.selectByIndex(i);
System.out.println("Not Working :"+i);
waitForWebPagetoLoad(2000);
WebElement search_BTN=Fn_GetWebElement(CreateSSIObject.getProperty("search_Btn"));
fn_Click(search_BTN);

WebElement  add_VEND=Fn_GetWebElement(CreateSSIObject.getProperty("add_vendors"));
fn_Click(add_VEND);
WebElement  vendorName=Fn_GetWebElement(CreateSSIObject.getProperty("vendor_Name"));
fn_Click(vendorName);
vendorName.sendKeys(vendor);
waitForWebPagetoLoad(5000);
WebElement  search_BTN1=Fn_GetWebElement(CreateSSIObject.getProperty("search_Btn"));
fn_Click(search_BTN1);
WebElement  selectVendor=Fn_GetWebElement(CreateSSIObject.getProperty("select_Vendor"));
fn_Click(selectVendor);
WebElement  addToSite=Fn_GetWebElement(CreateSSIObject.getProperty("AddTo_Site"));
fn_Click(addToSite);
}
}

在这里,我正在搜索一个元素(基本上是下拉 id(,然后使用 选择byindex 和 i for 循环选择每个值。 然后我单击一个按钮并对其执行更多操作。现在它只选择第一个值并执行上述所有操作。但它不会返回 for 循环以选择第二个值并执行相同的步骤。

我不太了解您的问题,但我可以看到 2 个可能会增加混乱的问题。

索引应基于 0

您的循环从 i 设置为 1 开始。 由于列表是从零开始的索引,因此应从 0 开始

引用过时的元素??

您将在循环外部提取下拉值,然后使用 index 在循环中引用这些值。 但是,您在每次迭代中都会执行大量操作和事件。

最好在每次迭代中再次提取值,以确保所有引用都是最新的并且没有过时。

你能试试下面的解决方案吗?我不确定您尝试根据选择执行什么操作,但我认为下面的代码可以解决您的问题。

Select drpCountry = new Select(driver.findElement(By.name("Locator")));
List <WebElement> elementCount = drpCountry.getOptions();
int iSize = elementCount.size();
for(int i =0; i<iSize ; i++)
{
String sValue = elementCount.get(i).getText();
System.out.println(sValue);
drpCountry.selectByIndex(i);
if(sValue.equalsIgnoreCase("Selection1")){  
//code to be executed if condition1 is true  
}else if(sValue.equalsIgnoreCase("Selection2")){  
//code to be executed if condition2 is true  
}  
else if(sValue.equalsIgnoreCase("Selection3")){  
//code to be executed if condition3 is true  
}  
else{  
//code to be executed if all the conditions are false  
}  
}

最新更新