我在网页上有多个链接。单击链接后,将打开一个弹出窗口,我在弹出窗口中的字段上设置一些值,然后单击“保存”。
单击“保存”后,主网页会刷新以显示链接的更新状态。我使用“for”循环逐个遍历所有链接并更新状态。为了避免过时的元素引用,我编写了一个实用程序来检查元素是否仍然过时,但我无法摆脱这个异常。
下面是我的实用程序代码:
public static boolean isStale(WebElement e){
try{
e.isDisplayed();
return false;
}catch(StaleElementReferenceException ex){
return true;
}
}
下面是我的页面对象代码:
public class DocCheckPageObjects {
WebDriver driver = null;
public DocCheckPageObjects(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(tagName="a")
WebElement tagName_a;
public WebElement tagName_a() { return tagName_a; }
@FindBy(xpath="//input[@name='progress']")
WebElement listBoxDocStatus;
public WebElement listBoxDocStatus() { return listBoxDocStatus; }
@FindBy(xpath="//span[@title='Received Hard Copy']")
WebElement listBoxDocStatusOptionReceivedHardCopy;
public WebElement listBoxDocStatusOptionReceivedHardCopy() { return listBoxDocStatusOptionReceivedHardCopy; }
@FindBy(xpath="//button[@name='update']")
WebElement btnSave;
public WebElement btnSave() { return btnSave; }
@FindBy(xpath="//*[contains(text(),'Saved Successfully')]")
WebElement toastMsg;
public WebElement toastMsg() { return toastMsg; }}
下面是我的类代码:
DocCheckPageObjects docCheckObj = new DocCheckPageObjects(driver);
WebElement docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));
System.out.println("No of Links: " + docCheckTable.findElements(By.tagName("a")).size());
int linkCount = docCheckTable.findElements(By.tagName("a")).size();
for(int i=0; i<linkCount;i++) {
wait.until(ExpectedConditions.elementToBeClickable(docCheckTable.findElements(By.tagName("a")).get(i)));
docCheckTable.findElements(By.tagName("a")).get(i).click();
docCheckObj.listBoxDocStatus().click();
docCheckObj.listBoxDocStatusOptionReceivedHardCopy().click();
docCheckObj.btnSave().click();
while(util.isStale(docCheckTable.findElements(By.tagName("a")).get(i))) {
docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));
}
}
我认为 while 循环中的代码在刷新页面之前执行,因此我仍然遇到过时元素异常。
下面是使用 thread.sleep 工作的代码:
for(int i=0; i<linkCount;i++) {
Thread.sleep(1000);
docCheckTable = driver.findElement(By.xpath("//div[@class='slds-gutters slds-wrap slds-m-horizontal_xx-small']/table"));
wait.until(ExpectedConditions.elementToBeClickable(docCheckTable.findElements(By.tagName("a")).get(i)));
docCheckTable.findElements(By.tagName("a")).get(i).click();
docCheckObj.listBoxDocStatus().click();
docCheckObj.listBoxDocStatusOptionReceivedHardCopy().click();
docCheckObj.btnSave().click();
}
Q1)上面的代码解析了状态元素引用,但我想避免使用thread.sleep。
Q2)我不得不把我的定位器像“docCheckTable”放在我的可执行类中,而不是放在页面对象工厂类中。如何将我的所有定位器放在返回 Web 元素列表并避免过时元素异常的页面对象类中。