我正在尝试从 Datepicker 中选择日期。以下是代码
WebDriver d=new FirefoxDriver();
Actions a=new Actions(d);
String date="14";
d.get("http://www.eyecon.ro/bootstrap-datepicker/");
d.findElement(By.cssSelector("div#dp3>span")).click();
List<WebElement> trs=d.findElements(By.cssSelector("div.datepicker-days>table>tbody>tr"));
for(WebElement tr:trs) {
List<WebElement> tds=tr.findElements(By.tagName("td"));
for(WebElement td:tds) {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
}
}
}
使用上面的代码,我在这行代码处得到了陈旧的元素引用异常
"if(date.equals(td.getText())) {"
所以我把代码改成了这个
for(WebElement td:tds) {
while(i<4) {
try {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
}
break;
}catch(Exception ex) {
}
System.out.println(i);
i++;
}
}
现在我可以选择日期。但是脚本仍然抛出过时的元素引用异常。脚本现在在这一行显示错误
List<WebElement> tds=tr.findElements(By.tagName("td"));
过去 3 天我一直在研究这个问题。关于如何解决这个问题的任何建议。
提前致谢
最佳答案
在您的第一个代码中,在您单击元素后,DOM 发生了变化,因为 Date 变成了 "14" ,并且由于 for 循环仍在迭代,因此它抛出 StaleElementReferenceException .
同样,在第二个代码中,您确实破坏了 “内部 for 循环”那是在迭代 td 元素,但您没有破坏 “外面”一,继续迭代 tr 元素,因此它抛出 StaleElementReferenceException 再次。
分辨率:- 你应该使用 break 从两个 for 循环中出来单击元素后,因此 在此过程中避免 StaleElementReferenceException。
下面的代码显示了如何毫无异常(exception)地跳出两个 for 循环:
WebDriver d=new FirefoxDriver();
d.manage().window().maximize(); //Maximizing window
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Implicit wait for 20 seconds
Actions a=new Actions(d);
String date="14";
int flag=0;
d.get("http://www.eyecon.ro/bootstrap-datepicker/");
d.findElement(By.cssSelector("div#dp3>span")).click();
List<WebElement> trs=d.findElements(By.cssSelector("div.datepicker-days>table>tbody>tr"));
for(WebElement tr:trs) {
List<WebElement> tds=tr.findElements(By.tagName("td"));
for(WebElement td:tds) {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
flag=1; // Set to 1 when the required element was found and clicked.
break; //To come out of the first for-loop
}
}
if(flag==1)
break; //Since the element was found, come out of the second for-loop.
}
注意:- 我已经添加了最大化窗口和提供隐式等待的代码,这实际上是在编写 selenium 脚本时建议的。
关于selenium - 尝试从日期选择器中选择日期时如何修复 'stale element reference exception'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453068/