2015-10-02 87 views
1

以下代码使用JXL插件读取电子表格单元格值,然后将这些值与页面上的值进行比较,并从组合框中选择匹配值。将值与Selenium和JXL进行比较

我的代码有效,但区分大小写,值必须相同。 我想改进此代码以更快地搜索组合框,并选择最接近的值而不相同。目前它缓慢地贯穿所有值。

String valDesejado = tipopromocao; 
String valorComboBox = ""; 
Select verificaOpt = new Select(driver.findElement(By.name("tipoDePromocaoPromocao"))); 

int tamanhoBox = verificaOpt.getOptions().size(); 
int variavelVerificadora1 = 0; 
System.out.println("Tamanho: " + tamanhoBox); 

for (int i = 0; i < tamanhoBox; i++) 
{ 
    verificaOpt.selectByIndex(i); 
    valorComboBox = verificaOpt.getFirstSelectedOption().getText().toString(); 

    if (valDesejado.equalsIgnoreCase(valorComboBox)) 
    { 
     i = tamanhoBox; 
     variavelVerificadora1 = 1; 
    } 

} 
if (variavelVerificadora1 == 0) 
{ 
    System.out.println("ALERTA: The Option + valDesejado + " no comboBox \"tipoDePromocaoPromocao\" not found."); 
} 
+1

快速评论...你在这里缺少一个右引号“ ”ALERTA:期权+ ...'应该是'。“ ALERTA:选项” + ...' – JeffC

回答

1

我在代码中提出了一些注释,解释了我在做什么,并对几件事情进行了更正。

  1. 而不是使用int并将其设置为0/1的,使用boolean并将其设置为真/假。
  2. 此循环应该更快,因为我没有选择每个选项,因为我循环。您可以检查每个选项的文本而不选择它,然后一旦找到匹配项,请选择匹配项。
  3. 使用break退出循环,而不是将计数器设置为最大值。

给这段代码试一试。

String valDesejado = tipopromocao; 
boolean variavelVerificadora1 = false; // use boolean instead of int set to 0/1 
Select verificaOpt = new Select(driver.findElement(By.name("tipoDePromocaoPromocao"))); 
System.out.println("Tamanho: " + verificaOpt.getOptions().size()); 
// as this loops, the variable 'option' contains the current loops' OPTION element 
// you don't need to select the option to get its text so this loop should be much faster 
// it selects the OPTION once the correct one is found 
for (WebElement option : verificaOpt.getOptions()) 
{ 
    if (valDesejado.equalsIgnoreCase(option.getText())) 
    { 
     verificaOpt.selectByVisibleText(option.getText()); // select the OPTION match 
     variavelVerificadora1 = true; // set the boolean to true to indicate we found a match 
     break; // exits the for loop 
    } 
} 

if (!variavelVerificadora1) // this is the equivalent of variavelVerificadora1 == false, it's basically saying if not true 
{ 
    System.out.println("ALERTA: The Option" + valDesejado + " no comboBox \"tipoDePromocaoPromocao\" not found."); 
} 
+0

谢谢,工作完美。快速有效。 –