首页 > 解决方案 > 如何在 Selenium [C#] 中添加单个等待两个不同元素

问题描述

我的应用程序中有两个不同的表单,表单输入数据加载可以使用 UI 中可用的预定义模板完成(即,输入文本字段值将根据模板选择预先填充)。当数据加载发生时,元素渲染不会发生,只会填充输入字段值。为了确认数据加载,我使用如下等待

var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(60));

wait.Until(x => x.FindElement(By.XPath(Element1_FieldXPath)).GetAttribute("value").Length > 1);

在任何时候,单独的 Form1 或 Form2 都是可见的。因此,我需要确认 Form1 或 Form2 中的数据加载。所以,我需要编写一个通用方法来处理这种情况,我遇到了以下解决方案,

public bool IsDataLoadingCompleted()
{
   var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(60));

   try
   {
       wait.Until(x => x.FindElement(By.XPath(Form1_FieldXPath)).GetAttribute("value").Length > 1);
       return true;
   }
   catch (TimeoutException)
   {
       try
       {
           wait.Until(x => x.FindElement(By.XPath(Form2_FieldXPath)).GetAttribute("value").Length > 1);
           return true;
       }
       catch (TimeoutException)
       {
           return false;
       }
   }      
}

在我的解决方案中,最坏情况的等待时间是120s当 form2 在 UI 中可见时。我需要用单等待而不是双等待来解决上述问题。

有没有其他方法可以用最少的等待时间解决问题?

示例 HTML:

表单 1 - 字段 1 HTML:

<div class="form-group field field-string">
    <label class="control-label" for="root_employeeName">Employee name</label>
    <input class="form-control" id="root_employeeName" label="Employee name" placeholder="" type="text" value="">
</div>

表单 2 - 字段 1 HTML:

<div class="form-group field field-string">
    <label class="control-label" for="root_employeeAddress">Employee Address</label>
    <input class="form-control" id="root_employeeAddress" label="Employee Address" placeholder="" type="text" value="">
</div>

标签: c#seleniumselenium-webdrivercss-selectorswebdriverwait

解决方案


我假设始终显示一种形式,并且定位器具有静态id

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("input[class='form-control']")))
string elementid = FindElement(By.CssSelector("input[class='form-control']")).GetAttribute("id") // or GetAttribute("label") 
if(elementid=="root_employeeName"){
 // do your action here if name form is displayed
}
else if(elementid=="root_employeeAddress"){
// do you action here if Address form is displayed
}

推荐阅读