【发布时间】:2014-06-06 04:27:29
【问题描述】:
我的应用程序必须在 IE 中使用。我正在自动化测试,其中脚本首先必须在第一个下拉框“类别”中选择一个选项,以便在第二个下拉框“名称”中显示与类别相关的选项。然后脚本在“名称”中选择一个选项,并显示相关页面。
在“类别”中进行选择之前,“名称”没有任何选项。 HTML 源代码:
<select id="drop_Category">
<option value =""/>
<option value = "Category1">
Text - Category1
<option value = "Category2">
Text - Category2
<select id="drop_Name">
选择“Category1”选项后,HTML 源代码变为:
<select id="drop_Category">
<option value =""/>
<option value = "Category1">
Text - Category1
<option value = "Category2">
Text - Category2
<select id="drop_Name">
<option value =""/>
<option value = "C1_Name1">
Text - C1_Name1
<option value = "C1_Name2">
Text - C1_Name2
<option value = "C1_Name3">
Text - C1_Name3
对于选择“Category1”和“C1_Name3”的脚本,我的第一个版本代码是:
//Select option in drop-box "Category"
stringText = "Category1";
var dropCategory = new SelectElement(driver.FindElement(By.Id("drop_Category")));
dropCategory.SelectByText(stringText);
//Select option in drop-box "Name"
stringText = "C1_Name3";
var dropName = new SelectElement(driver.FindElement(By.Id("drop_Name")));
dropName.SelectByText(stringText);
此代码不起作用,因为“名称”中的列表尚未加载,脚本找不到带有文本“C1_Name3”的选项,所以我添加了隐式等待。等待没有帮助,所以我试图捕捉异常。这是第二版代码:
//Select option in drop-box "Category"
stringText = "Category1";
var dropCategory = new SelectElement(driver.FindElement(By.Id("drop_Category")));
dropCategory.SelectByText(stringText);
//Select option in drop-box "Name"
stringText = "C1_Name3"
try
{
var dropName = new SelectElement(driver.FindElement(By.Id("drop_Name")));
dropName.SelectByText(stringText);
}
catch (NoSuchElementException)
{
var dropName = new SelectElement(driver.FindElement(By.Id("drop_Name")));
dropName.SelectByText(stringText);
}
它工作但有时由于 InvalidSelectorException 或 StaleElementReferenceException 异常仍然崩溃。我不知道该怎么做才能始终如一地完成这项工作。另外,我是该领域的新手,所以我不确定在我的第二个版本中编写代码是否是不好的做法。非常感谢任何帮助。
【问题讨论】:
-
如果元素需要时间才能出现并可用,为什么不使用显式等待?
标签: c# internet-explorer selenium driver