显示堆栈溢出的错误
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","/home/arima/chromedriver/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://education-india.in/Education/Courses/?PageNumber=1");
Thread.sleep(5000);
List<WebElement> dropdown = driver.findElements(By.xpath("//select[@id='txtPageNumber']/option"));
for(int k=1;k<dropdown.size()-1;k++) {
List<WebElement> rows = driver.findElements(By.xpath("//table[@class='index']/tbody/tr"));
List<WebElement> col = driver.findElements(By.xpath("//table[@class='index']/tbody/tr[1]/th"));
for(int i=0;i<rows.size()-1;i++){
System.out.println(rows.get(i).getText());
}
dropdown.get(k).click();
Thread.sleep(4000);
/*
* WebDriverWait wait = new WebDriverWait(driver, 10);
* wait.until(ExpectedConditions.presenceOfElementLocated(dropdown));
*/
}
}
答案 0 :(得分:0)
stale element reference: element is not attached to the page document
当webdriver无法识别该页面上的元素时出现错误。您需要在drop loop中重新分配您的下拉元素。尝试以下代码。
driver.get("http://education-india.in/Education/Courses/?PageNumber=1");
WebDriverWait wait=new WebDriverWait(driver, 30);
List<WebElement> dropdown =wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//select[@id='txtPageNumber']/option")));
for(int k=1;k<dropdown.size()-1;k++) {
List<WebElement> newdropdown =wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//select[@id='txtPageNumber']/option")));
List<WebElement> rows = driver.findElements(By.xpath("//table[@class='index']/tbody/tr"));
List<WebElement> col = driver.findElements(By.xpath("//table[@class='index']/tbody/tr[1]/th"));
for(int i=0;i<rows.size()-1;i++){
System.out.println(rows.get(i).getText());
}
newdropdown.get(k).click();
}
答案 1 :(得分:0)
由于下拉列表是一个选择元素。您可以使用选择对象来选择页面。
过时的元素引用错误的原因是每次页面加载时,下拉菜单的定位符保持不变,但元素不同。下拉菜单也会刷新。这就是为什么每次页面加载后都必须找到下拉菜单的原因。
尝试一下:
driver.get("http://education-india.in/Education/Courses/?PageNumber=1");
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.id("txtPageNumber")));
List<WebElement> options = driver.findElements(By.xpath("//select[@id='txtPageNumber']/option"));
for (int k = 0; k<options.size(); k++) {
new Select(driver.findElement(By.xpath("//select[@id='txtPageNumber']"))).selectByIndex(k);
List<WebElement> rows = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//table[@class='index']/tbody/tr")));
List<WebElement> col = driver.findElements(By.xpath("//table[@class='index']/tbody/tr[1]/th"));
for (int i = 0; i < rows.size()-1; i++) {
System.out.println("PRE: "+rows.get(i).getText());
}
}