2015-10-02 126 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

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