赞同来自:
使用findElements而不是findElement。
如果未找到匹配的元素而不是异常,findElements将返回一个空列表。
要检查元素是否存在,您可以尝试这样做
Boolean isPresent = driver.findElements(By.yourLocator).size() > 0如果找到至少一个元素,则返回true,如果不存在则返回false。
赞同来自:
我在Java中找到的最简单的方法是:
List linkSearch= driver.findElements(By.id("linkTag"));
int checkLink=linkSearch.size();
if(checkLink!=0){ //do something you want}
尝试这个:
调用此方法并传递3个参数:
WebDriver变量。 //假设driver_variable为驱动程序。
您要检查的元素。应该从By方法提供。 // ex:By.id(“id”)
以秒为单位的时间限制。
示例:waitForElementPresent(driver,By.id(“id”),10);
public static WebElement waitForElementPresent(WebDriver driver, final By by, int timeOutInSeconds) {
WebElement element;
try{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait()
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //reset implicitlyWait
return element; //return the element
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
赞同来自:
我会使用类似的东西(使用Scala [旧的代码“好”Java 8可能与此类似]):
object SeleniumFacade {
def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
val elements = maybeParent match {
case Some(parent) => parent.findElements(by