我正在使用 Selenium 做一个 C# 项目。我需要检查一个元素是否存在?
举个例子
var userNameField = driver.FindElementById("id_email");
userNameField.SendKeys("xxxxx");
如果 userNameField 在网页中不存在,则某些代码不能工作,其他部分必须工作。 有什么建议..?
最佳答案
除了使用 FindElementById,您还可以尝试使用 FindElements,它将返回一个列表,其中包含与您的搜索相对应的所有可能元素。然后你可以测试这个列表是否为空,并根据答案执行相应的代码。
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.
}
关于c# - 如果在 Selenium C# 中有其他条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44306974/