我需要使用 selenium 检查当前网页中是否存在表单元素。有人知道该怎么做吗?
3 回答
There are two ways to do this. Either use lefthandedgoat's version catching an exception, or use the FindElements method and check it's size, so something like (in C# using LINQ):
public bool IsElementPresent(By selector)
{
return driver.FindElements(selector).Any();
}
Either option will work fine, there is not really much different. I personally use the other way, but wanted to make sure you knew there are generally two ways to do this. You didn't mention a language, so let us know if there is a specific language you are using.
It is worth noting that underneath, when you do a FindElement() in Selenium, it is performing this method.
在 selenium 的 C# 版本中,如果元素不存在,它将引发异常。你可以做这样的事情
public bool Exists(string cssSelector)
{
try
{
browser.FindElement(By.CssSelector(cssSelector));
return true
}
catch (Exception ex){}
return false;
}
var exists = Exists("form");
我不确定 webdriver 在其他语言中的行为方式。
您可以使用两种方法:
input.findElements(By.xpath("//....blablalba....")).size() > 0
driver.findElement(By.xpath("//....blablalba....")).isDisplayed()