gpt4 book ai didi

java - 如何迭代每个循环以获取重复值

转载 作者:太空宇宙 更新时间:2023-11-04 10:48:48 25 4
gpt4 key购买 nike

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

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

如何克服这个错误?

注意:-“我所需的 Web 元素是给定合约 ID 列表中的第三个”。

// 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);

}
}
}

最佳答案

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

您期望能够访问列表 [rows] 中的元素,该元素在执行 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);

关于java - 如何迭代每个循环以获取重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48079650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com