Java 通过使用WebElement而不是By的方法对Allelement进行延迟的呈现
我正在使用PageFactory定位元素,我需要等待元素不存在 我的等待方法如下:Java 通过使用WebElement而不是By的方法对Allelement进行延迟的呈现,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我正在使用PageFactory定位元素,我需要等待元素不存在 我的等待方法如下: public void waitForElementIsNoExists(By by) { try { FluentWait<WebDriver> myWait = new FluentWait<WebDriver>(driver) .withTimeout(timeOut, TimeUnit.SECONDS)
public void waitForElementIsNoExists(By by) {
try {
FluentWait<WebDriver> myWait = new FluentWait<WebDriver>(driver)
.withTimeout(timeOut, TimeUnit.SECONDS)
.pollingEvery(50, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class)
.ignoring(TimeoutException.class);
myWait.until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(by)));
} catch (TimeoutException e) {
System.out.println("Timed out after default time out. Page is not responding after " + timeOut + "sec.");
}
}
public void waitForElementIsNoExists(By){
试一试{
FluentWait myWait=新FluentWait(驱动程序)
.withTimeout(超时,时间单位为秒)
.pollingEvery(50,时间单位为毫秒)
.忽略(NoSuchElementException.class)
.忽略(StaleElementReferenceException.class)
.忽略(TimeoutException.class);
myWait.until(ExpectedConditions.not(ExpectedConditions.presence of allelements slocatedby(by));
}捕获(超时异常e){
System.out.println(“在默认超时后超时。页面在“+超时+”秒之后没有响应”);
}
}
通过Selenium API实现延迟的Allelements的存在:
public static ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy(final By locator) {
return new ExpectedCondition<List<WebElement>>() {
public List<WebElement> apply(WebDriver driver) {
List<WebElement> elements = ExpectedConditions.findElements(locator, driver);
return elements.size() > 0 ? elements : null;
}
public String toString() {
return "presence of any elements located by " + locator;
}
};
}
public static ExpectedCondition存在被锁定的所有成员(定位器最终){
返回新的ExpectedCondition(){
公共列表应用(WebDriver){
列表元素=ExpectedConditions.findElements(定位器、驱动程序);
返回元素.size()>0?元素:null;
}
公共字符串toString(){
返回“+定位器定位的任何元素的存在;
}
};
}
但是,由于PageFactory,我需要使用WebElement而不是by
如何重写PresenceOfAllElementsLocated方法以获取WebElement作为参数?因此,PageFactory可以避免StaleElementException
谢谢 不需要重写内置方法。如果您有一个
WebElement
,您可以使用以下方法检查它是否不存在(或者至少不存在,它在页面上不再可见):
不要使用pageFactory使用下面的代码 1.在页面对象类中,定义web元素如下 By元素=By.xpath(//select[@id='******']” 网络元素 2.创建一个CommonMethod.java类并编写下面的方法2 私有静态WebDriverWait jsWait=新WebDriverWait(驱动程序,60) 公共静态WebElement getWebelement(WebDriver驱动程序,按) { WebElement ele=null
try {
ele =Findelement(by);
} catch (StaleElementReferenceException ignored) {
Findelement(by);
}
return ele;
}
公共静态WebElement Findelement(按)
3.调用此方法
getWebelement(驱动程序,元素)
try {
ele =Findelement(by);
} catch (StaleElementReferenceException ignored) {
Findelement(by);
}
return ele;
}
{
jsWait.until(ExpectedConditions.visibilityOfElementLocated((by)));
WebElement ele = driver.findElement(by);
return ele;
}