我通常使用两种方法(成对)来验证元素是否存在:
public boolean isElementPresent(By locatorKey) { try { driver.findElement(locatorKey); return true; } catch (org.openqa.selenium.NoSuchElementException e) { return false; }}public boolean isElementVisible(String cssLocator){ return driver.findElement(By.cssSelector(cssLocator)).isDisplayed();}请注意,硒有时可以在DOM中找到元素,但是它们是不可见的,因此硒将无法与其交互。因此,在这种情况下,检查可见性的方法会有所帮助。
如果要等到元素出现,我发现最好的解决方案是使用流畅的等待:
public WebElement fluentWait(final By locator){ Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); return foo;};希望这可以帮助)



