如何为每个循环迭代重复值

问题描述 投票:1回答:1

我期望发生的事情:程序应该从列表中找到预期的Web元素,单击它,找到合同ID并与给定的合同ID匹配。如果是,则中断循环,否则单击后退按钮继续,直到满足条件。

实际问题:为每个循环运行此操作;程序在列表中找到第一个web元素,并传递第一个if条件。在单击web元素之后,由于第二个if条件不满足,它将退出循环并再次检查每个循环,但程序或代码在此处中断并抛出错误,如“陈旧元素引用:元素未附加到页面文档“:(

如何克服这个错误?

注意: - “我所需的Web元素在给定合同ID的列表中是第3位”。

// Selenium Web Driver with Java-Code :-    
WebElement membership = driver.findElement(By.xpath(".//*[@id='content_tab_memberships']/table[2]/tbody"));

List<WebElement> rownames = membership.findElements(By.xpath(".//tr[@class='status_active']/td[1]/a"));
// where rownames contains list of webElement with duplicate webElement names  eg:- {SimpleMem, SimpleMem , SimpleMem ,Protata} but with unique contarct id (which is displayed after clicking webElement)

for (WebElement actual_element : rownames) {
    String Memname = actual_element.getAttribute("innerHTML");
    System.out.println("the membershipname"+  Memname);

    if (Memname.equalsIgnoreCase(memname1)) {
        actual_element.click();  
        String actualcontractid = cp.contarct_id.getText();

        if (actualcontractid.equalsIgnoreCase(contractid)) {
            break;
        } else {
            cp.Back_Btn.click();
            Thread.sleep(1000L);

        }
    }
}
java selenium foreach
1个回答
0
投票

单击row元素后,您将离开当前页面DOM。在新页面上,如果不匹配合同ID,则您将导航回上一页。

您期望您应该能够访问前面执行foreach循环时出现的列[行]中的元素。但是现在DOM被重新加载,之前的元素无法访问,因此Stale Element Reference Exception

你可以试试下面的示例代码吗?

 public WebElement getRowOnMatchingMemberNameAndContractID(String memberName, String contractId, int startFromRowNo){
        WebElement membership = driver.findElement(By.xpath(".//*[@id='content_tab_memberships']/table[2]/tbody"));
        List<WebElement> rowNames = membership.findElements(By.xpath(".//tr[@class='status_active']/td[1]/a"));
// where rownames contains list of webElement with duplicate webElement names  eg:- {SimpleMem, SimpleMem , SimpleMem ,Protata} but with unique contarct id (which is displayed after clicking webElement)
        for(int i=startFromRowNo; i<=rowNames.size(); i++){
            String actualMemberName = rowNames.get(i).getAttribute("innerHTML");
            if(actualMemberName.equalsIgnoreCase(memberName)){
                rowNames.get(i).click();
                String actualContractId = cp.contarct_id.getText();
                if(actualContractId.equalsIgnoreCase(contractId)){
                    return rowNames.get(i);
                }else {
                    cp.Back_Btn.click();
                    return getRowOnMatchingMemberNameAndContractID(i+1);
                }
            }
        }
        return null;
    }

我已经使用递归和附加参数来处理先前单击的行。您可以使用0作为起始行调用上面的方法,如 -

WebElement row = getRowOnMatchingMemberNameAndContractID(expectedMemberName, expectedContractID,0);
© www.soinside.com 2019 - 2024. All rights reserved.