如果Selenium C中还有条件#

时间:2017-06-01 12:00:43

标签: c# selenium

我正在使用Selenium进行C#项目。我需要检查一个元素是否存在?

示例

var userNameField = driver.FindElementById("id_email");
userNameField.SendKeys("xxxxx");

如果网页中不存在 userNameField ,则某些代码必须无效,否则部分必须正常工作.. 有什么建议..?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用FindElements代替使用FindElementById,它将返回一个列表,其中包含与您的搜索相对应的所有可能元素。然后,您可以测试此列表是否为空,并根据答案执行相应的代码。

List<WebElement> rows = driver.FindElements(By.Id("id_email"));
if(rows.Count > 0)
{
    // The element exists. You can work with it.
    rows.First().SendKeys("xxxxx");
}
else
{
    // The element doesn't exist.
}

答案 1 :(得分:1)

您可以使用try catch来完成这项工作。 如果webdriver无法找到一个元素,它将抛出NoSuchElementException。

IWebElement userNameField = null;
try 
{
    userNameField = driver.FindElementById("id_email");
}
catch(NoSuchElementException e)
{
    // If you are creating a unit test
    Assert.Fail("Element "userNameField" not found.")
}

// If you just want the if:
if(userNameField != null)
{
    userNameField.SendKeys("xxxxx");
}
else 
{
    // do your thing
}