Selenium:如何定位动态元素(如通知消息)
我正在将Selenium与Web驱动程序一起使用 我有一张表格要填在灯箱里。现在当我点击“提交”时。那个灯箱被关闭,一个简单的通知在页面顶部生成,几秒钟后就消失了 现在我的问题是:我什么时候做Selenium:如何定位动态元素(如通知消息),selenium,selenium-webdriver,xpath,Selenium,Selenium Webdriver,Xpath,我正在将Selenium与Web驱动程序一起使用 我有一张表格要填在灯箱里。现在当我点击“提交”时。那个灯箱被关闭,一个简单的通知在页面顶部生成,几秒钟后就消失了 现在我的问题是:我什么时候做 driver.findElement(By.xpath(".//*[@id='createCaseBtn']")).click(); // x-path of submit button 如何检查该通知消息是否出现在UI上 因为当我这么做的时候 driver.findElement(By.xpath("
driver.findElement(By.xpath(".//*[@id='createCaseBtn']")).click(); // x-path of submit button
如何检查该通知消息是否出现在UI上
因为当我这么做的时候
driver.findElement(By.xpath(".//*[@id='easyNotification']")).getText(); // x-path of easyNotification message
我告诉我,它无法找到逻辑上似乎正确的元素,因为此时UI上不存在通知消息。只有在完成AJAX请求(提交表单)之后,消息才会出现在UI上
请帮忙
很好,谢谢。当我处理AJAX时,我总是使用流畅的等待方法。 假设您在单击“提交”按钮后出现了消息的定位器:
String xPathMessage= ".//*[@id='easyNotification']";
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; } ;
//simply call the method:
String text=fluentWait(By.xpath(xPathMessage)).getText();
或者:
public bool isElementPresent(By selector)
{
return driver.FindElements(selector).size()>0;
}
希望这对您有用使用显式等待。这对我来说很好: 显式等待是您定义的代码,用于在继续执行代码之前等待特定条件发生。最糟糕的情况是Thread.sleep(),它将条件设置为等待的确切时间段。提供了一些方便的方法,可以帮助您编写只在需要时等待的代码。WebDriverWait与ExpectedCondition相结合是实现这一目标的一种方法
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id(".//*[@id='easyNotification']")));
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id(".//*[@id='easyNotification']")));