java - 为什么我的所有页面数据都显示 StaleElementReferenceException

标签 java selenium selenium-webdriver

显示堆栈溢出错误

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

最佳答案

stale element reference: element is not attached to the page document 

当 webdriver 无法识别该页面上的元素时,就会出现错误。您需要在 for 循环内重新分配下拉元素。请尝试以下代码。

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

        }

关于java - 为什么我的所有页面数据都显示 StaleElementReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020600/

相关文章:

java - Maven -Dtest=* test,似乎没有运行所有测试

java - 如何在android中将数据库文件附加到apk文件

java - 用 Java 读取 CSV 文件的最快方法

java - 为什么我们在selenium中将URL变量声明为私有(private)静态字符串?

java - 我在网页中有一个表格,其中有一个如图所示的界面。通过匹配接口(interface)名称,我需要单击箭头

java - 如何从java中的结果集中返回多行?

python - 如何使用 Selenium 单击打开的应用程序警报

java - 指标、气味 : How to find longest (in lines of code) methods in my legacy product java repo?

java - JSR 303 自定义约束覆盖

java - 搜索第 n 个命中时无法使用 Selenium 找到现有元素