【问题标题】:Selenium webdriver: if condition for a long list of objectsSelenium webdriver:如果条件为一长串对象
【发布时间】:2015-08-24 10:28:30
【问题描述】:

有没有办法简化下面的代码?

public static void InputData(){
 //Lastname
 if (driver.findElements(By.id("last_name")).size() != 0) {  
 driver.findElement(By.id("last_name")).sendKeys("MARSUPIAL");
 } 
 //Fistname
 if (driver.findElements(By.id("first_name")).size() != 0) {  
 driver.findElement(By.id("first_name")).sendKeys("MARK"); 
 } 

}

我有 20 件物品具有相同的“如果”场景

有没有办法在单个 if 语句中编写它而不是在每个文本框中执行“如果对象存在写入 'x'”?

提前致谢

【问题讨论】:

    标签: java selenium if-statement automation webdriver


    【解决方案1】:

    一种可能性是将密钥放在Map 和 遍历Map 进行验证:

    final Map<String,String> lAllKeys = new HashMap<>();
    lAllKeys.put("last_name","MARSUPIAL");
    lAllKeys.put("first_name", "MARK");
    for (String lKey : lAllKeys.keySet()) {
      if (driver.findElements(By.id(lKey)).size() != 0) {  
         driver.findElement(By.id(lKey)).sendKeys(lAllKeys.get(lKey));
      } 
    }
    

    【讨论】:

    • 感谢@stefan,如果我有另一组但不使用 sendkeys,应该单击对象,例如 if (driver.findElements(By.xpath(".//*[@id='checkbox1 ']")).size() != 0) { driver.findElement(By.xpath(".//*[@id='checkbox1']")).click(); }
    • 你也可以用地图处理
    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多