Selenium webdriver 刷新网页时获取org.openqa.selenium.StaleElementReferenceException

Selenium webdriver 刷新网页时获取org.openqa.selenium.StaleElementReferenceException,selenium-webdriver,Selenium Webdriver,当我试图运行这段代码时,我得到org.openqa.selenium.StaleElementReferenceException:Element未在缓存中找到-可能页面在查找后已更改 命令持续时间或超时:10.05秒 基本上,我在类的开头声明了所有webelement变量,以减小代码的大小。但是当页面刷新时,StaleElementReferenceException就会出现 package musicshop; import java.util.concurrent.TimeUnit;

当我试图运行这段代码时,我得到org.openqa.selenium.StaleElementReferenceException:Element未在缓存中找到-可能页面在查找后已更改 命令持续时间或超时:10.05秒

基本上,我在类的开头声明了所有webelement变量,以减小代码的大小。但是当页面刷新时,StaleElementReferenceException就会出现

package musicshop;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class AddCustomerAdmin {

    public void addCustomerAdmin(WebDriver driver) throws InterruptedException{ 


        //Clicking on 'Customer' in the left side bar in admin panel
        driver.findElement(By.xpath("html/body/div[2]/aside/div/section/ul/li[2]/a/span")).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);



        // Clicking on 'Add Customer' button        
        driver.findElement(By.xpath(".//*[@id='userform']/section[1]/div/div[2]/input")).click();
        Thread.sleep(1000);         





        WebElement firstName = driver.findElement(By.id("fname"));
        WebElement lastName = driver.findElement(By.id("lname"));
        WebElement accountEmail = driver.findElement(By.xpath(".//*[@id='email']"));
        WebElement checkbox = driver.findElement(By.id("subscribe_promo_email"));
        WebElement dateOfBirth = driver.findElement(By.id("date_of_birth"));
        WebElement phone = driver.findElement(By.id("phone"));
        WebElement address = driver.findElement(By.id("address"));          

        WebElement country = driver.findElement(By.id("countryid"));
        Select countryName = new Select(country);

        WebElement state = driver.findElement(By.id("stateid"));
        Select stateName = new Select(state);   

        WebElement city = driver.findElement(By.id("cityid"));
        Select cityName = new Select(city);

        WebElement zipcode = driver.findElement(By.id("postal_code"));      




        WebElement uploadImage = driver.findElement(By.id("fileupload"));       
        WebElement saveButton = driver.findElement(By.xpath(".//*[@id='userform']/section[1]/div/div[2]/input[2]"));        
        WebElement shippingAddressCheckbox = driver.findElement(By.id("shippingaddress"));




        WebElement shippingAddress = driver.findElement(By.id("sh_address"));

        WebElement shippingCountry = driver.findElement(By.id("sh_countryid"));
        Select shippingCountryName = new Select(shippingCountry);

        WebElement shippingState = driver.findElement(By.id("sh_stateid"));
        Select shippingStateName = new Select(shippingState);

        WebElement shippingCity = driver.findElement(By.id("sh_cityid"));
        Select shippingCityName = new Select(shippingCity);

        WebElement shippingZipCode = driver.findElement(By.id("sh_postal_code"));
        WebElement shippingPhoneNumber = driver.findElement(By.id("sh_phone"));






        // Add Customer page validation checking by keeping all fields empty and click on 'save' button
        saveButton .click();
        Thread.sleep(1000);         



        // Add Customer page validation checking by only entering first name and click on 'save' button
        firstName.sendKeys("John");
        saveButton .click();        
        Thread.sleep(500);          
        firstName.clear();      



        // Add Customer page validation checking by only entering last name and click on 'save' button
        lastName.sendKeys("Smith");
        saveButton.click();     
        Thread.sleep(500);          
        lastName.clear();   




        // Add Customer page validation checking by only entering account email and click on 'save' button          
        accountEmail.sendKeys("john@gmail.com");
        saveButton.click();     
        Thread.sleep(500);      
        accountEmail.clear();               



        // Add Customer page validation checking by only checking the 'Promotional Newsletter' checkbox and click on 'save' button
        checkbox.click();
        saveButton.click();     
        Thread.sleep(500);      
        checkbox.click(); // for unchecking the checkbox            



        // Add Customer page validation checking by only entering date of birth in the 'Date of Birth' field and click on 'save' button
        dateOfBirth.click();        
        for(int i=0; i<7; i++){         
            WebElement clickOnMonth = driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span"));
            clickOnMonth.click();           
        }       
        WebElement selectDate = driver.findElement(By.linkText("9"));
        selectDate.click(); 
        selectDate.click();

        for(int i = 0; i<=1; i++){      
        dateOfBirth.sendKeys(Keys.BACK_SPACE);      
        } //end of for loop

        dateOfBirth.sendKeys("88");     
        saveButton.click();     
        Thread.sleep(500);      
        dateOfBirth.clear();            




        // Add Customer page validation checking by only entering phone number in the 'Phone' field and click on 'save' button      
        phone.sendKeys("9999999999");       
        saveButton.click();      
        Thread.sleep(500);       
        phone.clear();      




        // Add Customer page validation checking by only entering address in the 'Address' field and click on 'save' button
         address.sendKeys("Minerva Garden, Joka, Kolkata");      
         saveButton.click();         
         Thread.sleep(500);      
         address.clear();        



        // Add Customer page validation checking by only entering country in the 'Country' field and click on 'save' button
         countryName.selectByVisibleText("India");       
         saveButton.click();    
         Thread.sleep(500);      



        // Add Customer page validation checking by only entering country and state in the 'Country' and 'State' field and click on 'save' button 
         stateName.selectByValue("41");
         saveButton.click();
         Thread.sleep(500);  



        // Add Customer page validation checking by only entering country, state, and city in the 'Country', 'State', and 'City' field and click on 'save' button 
         cityName.selectByVisibleText("Kolkata");
         saveButton.click();
         Thread.sleep(500);



         //deselecting City, State and Country fields
         cityName.selectByValue("");
         stateName.selectByValue("");
         countryName.selectByValue("");




        // Add Customer page validation checking by only entering zipcode in the 'ZIP/PIN' field and click on 'save' button 
         zipcode.sendKeys("222222");
         saveButton.click();
         Thread.sleep(500);
         zipcode.clear();


        /*----------------####@@@@****@@@@####----------------------------*/


         //Profile image upload where image height and width is less than 300px
         ((JavascriptExecutor) driver).executeScript("scroll(0,-400)"); // scrolling up the page
         driver.findElement(By.className("col-md-3")).click();       
         Thread.sleep(1000);


         uploadImage.sendKeys("C:\\Users\\QA-02\\Desktop\\rose3.jpg");
         Alert alert = driver.switchTo().alert();

         String comingAlertMessage = alert.getText(); // for capturing the alert message
         String alertMessageShouldDisplay = "image height or width cannot be less then 300px.";
         System.out.println(comingAlertMessage); // for displaying alert message


         if(comingAlertMessage.equals(alertMessageShouldDisplay)){

             System.out.println("Proper validation message is displaying");

         }else{         

             System.out.println("Proper validation message is not displaying");      
         }  


         Thread.sleep(1000);
         alert.accept();         

        /*------------------------###@@@@****@@@@####---------------------------*/ 



        //Profile image upload where image height and width is more than 300px
         Thread.sleep(1000);
         uploadImage.sendKeys("C:\\Users\\QA-02\\Desktop\\rose2.jpg");



        //Profile image changing where image height and width is more than 300px         
         Thread.sleep(1000);
         uploadImage.sendKeys("C:\\Users\\QA-02\\Desktop\\scene1.jpg");
         System.out.println("Profile image has changed successfully");   


         //'Add Customer' page refresh
         driver.navigate().refresh();

    /*-------------------------------####@@@@****@@@@####--------------------------------------*/    


         //Test the validation message of each mandatory field           

        for(int i=1; i<=11; i++){           


            if (i!=1){          


            firstName.sendKeys("John");
            Thread.sleep(500);      

            }

            if (i!=2){

            lastName.sendKeys("Smith");
            Thread.sleep(500);          

            }

            if (i!=3){

            accountEmail.sendKeys("frontendwebtesting@gmail.com");
            Thread.sleep(500);      

            }

            if (i!=4){

            checkbox.click();
            Thread.sleep(500);      

            }

            if (i!=5){

            dateOfBirth.sendKeys("05/13/1987");
            Thread.sleep(500);          

            }

            if (i!=6){

            phone.sendKeys("9999999999");
            Thread.sleep(500);      

            }

            if (i!=7){

            address.sendKeys("Tangra, Park Circus");
            Thread.sleep(500);      

            }

            if (i!=8){

             countryName.selectByVisibleText("India");
             Thread.sleep(500);         

            }

            if (i!=8 && i!=9){

            stateName.selectByVisibleText("West Bengal");
            Thread.sleep(500);      

            }

            if (i!=8 && i!=9 && i!=10){ 

            cityName.selectByVisibleText("Kolkata");
            Thread.sleep(500);          

            }

            if (i!=11){

            zipcode.sendKeys("222222");
            Thread.sleep(500);      

            }   

            saveButton.click();

           ((JavascriptExecutor) driver).executeScript("scroll(0,-400)"); //scrolling up the page
           Thread.sleep(1000);
           ((JavascriptExecutor) driver).executeScript("scroll(0,400)"); // scrolling down the page

           Thread.sleep(1000);         
           driver.navigate().refresh();        

        }    //end of for loop


        /*----------------------------------------------------------------------------------*/







        // Test 'Add Customer' by entering improper email id    

        for(int i = 1; i<=3; i++){

        firstName.sendKeys("John");     
        lastName.sendKeys("Smith"); 


        //for improper email id     
        if(i==1){
            accountEmail.sendKeys("frontendwebtesting");
        }
        else{           
            accountEmail.sendKeys("frontendwebtesting@gmail.com");          
        }       
        /*-----------------------##@@**@@##---------------------*/      



        checkbox.click();   


        // for improper date of birth - will check it later

        /*
        if(i==2){           
            dateOfBirth click();
            driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/table/tbody/tr[4]/td[3]/a")).click();

            for(int j=1; j<=8; j++){                
            dob.sendKeys(Keys.BACK_SPACE);                  
            }

            dob.sendKeys("777");            
        } // end of if

        */

        //else{         
        dateOfBirth.sendKeys("05/13/1987");     
        //}         
        /*---------------------------------------------------------------------*/




        //for improper phone number     
        if(i==2){           
            phone.sendKeys("66");               
        }       
        //else if(i==3){            
            //driver.findElement(By.id("phone")).sendKeys("1111222233334444");      
        //}     
        else{           
            phone.sendKeys("9999999999");       
        }       
        //-----------------------------------------------------------------//

        address.sendKeys("Tangra, Park Circus");
        countryName.selectByVisibleText("India");                   
        stateName.selectByVisibleText("West Bengal");
        cityName.selectByVisibleText("Kolkata");        
        zipcode.sendKeys("222222");

        if(i==3){

            shippingAddressCheckbox.click();
            ((JavascriptExecutor) driver).executeScript("scroll(0,600)");
            Thread.sleep(500);      


            String shAddress = shippingAddress.getAttribute("value");           
            String defaultAddress = address.getAttribute("value");             


            if (defaultAddress.equals(shAddress)){          

                System.out.println("Deault Address and Shipping Address is same");

        }else{

            System.out.println("                                               ");
            System.out.println("Deault Address and Shipping Address is not same");

            }       


            String shCountry = shippingCountryName.getFirstSelectedOption().getText();  
            String defaultCountry = countryName.getFirstSelectedOption().getText();     

            if(defaultCountry.equals(shCountry)){

                System.out.println("                                           ");
                System.out.println("Deault country and Shipping country is same");

            }else{

                System.out.println("Deault country and Shipping country is not same");

            }           


            String shState = shippingStateName.getFirstSelectedOption().getText();          
            String defaultState = stateName.getFirstSelectedOption().getText();

            if(defaultState.equals(shState)){


                System.out.println("                                       ");
                System.out.println("Deault state and Shipping state is same");

            }else{

                System.out.println("Deault state and Shipping state is not same");

            }           

            String shCity = shippingCityName.getFirstSelectedOption().getText();
            String defaultCity = cityName.getFirstSelectedOption().getText();

            if(defaultCity.equals(shCity)){

                System.out.println("                                     ");
                System.out.println("Deault city and Shipping city is same");

            }else{


                System.out.println("Deault city and Shipping city is not same");

            }       


            String shZip = shippingZipCode.getAttribute("value");
            String defaultZip = zipcode.getAttribute("value");

            if(defaultZip.equals(shZip)){

                System.out.println("                                           ");
                System.out.println("Deault zipcode and Shipping zipcode is same");

            }else{

                System.out.println("Deault zipcode and Shipping zipcode is not same");

            }   


            shippingAddress.click();;
            shippingAddress.clear();    
            Thread.sleep(500);          

            shippingCountryName.selectByValue("");
            Thread.sleep(500);          

            shippingCityName.selectByValue("");
            Thread.sleep(500);

            shippingZipCode.click();
            shippingZipCode.clear();
            Thread.sleep(500);          

            shippingPhoneNumber.click();
            shippingPhoneNumber.clear();
            Thread.sleep(500);

        }           

        saveButton.click();
        Thread.sleep(1000);


        if (driver.getTitle().contains("Database Error")){          

            Thread.sleep(500);          
            driver.navigate().to("http://lab-1.sketchdemos.com/musicshop/stores/musicshop/admin/customer.html");
        }

        driver.navigate().refresh();

        } // end of for loop

    }

}
package musicshop;
导入java.util.concurrent.TimeUnit;
导入org.openqa.selenium.Alert;
导入org.openqa.selenium.By;
导入org.openqa.selenium.JavascriptExecutor;
导入org.openqa.selenium.Keys;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebElement;
导入org.openqa.selenium.support.ui.Select;
公共类AddCustomerAdmin{
public void addCustomerAdmin(WebDriver驱动程序)引发中断异常{
//单击管理面板左侧栏中的“客户”
findelelement(By.xpath(“html/body/div[2]/aside/div/section/ul/li[2]/a/span”))。单击();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
//单击“添加客户”按钮
findelelement(By.xpath(“./*[@id='userform']]/section[1]/div/div[2]/input”)。单击();
睡眠(1000);
WebElement firstName=driver.findElement(By.id(“fname”);
WebElement lastName=driver.findElement(By.id(“lname”);
WebElement accountEmail=driver.findElement(By.xpath(“./*[@id='email']”);
WebElement复选框=driver.findElement(By.id(“订阅促销邮件”);
WebElement dateOfBirth=driver.findElement(By.id(“出生日期”);
WebElement phone=driver.findElement(By.id(“phone”);
WebElement地址=driver.findElement(By.id(“地址”));
WebElement country=driver.findElement(By.id(“countryid”);
选择国家名称=新选择(国家);
WebElement state=driver.findElement(By.id(“stateid”);
选择状态名称=新选择(状态);
WebElement city=driver.findElement(By.id(“cityid”);
选择城市名称=新建选择(城市);
WebElement zipcode=driver.findElement(By.id(“邮政编码”);
WebElement uploadImage=driver.findElement(By.id(“fileupload”);
WebElement saveButton=driver.findElement(By.xpath(“./*[@id='userform']]/section[1]/div/div[2]/input[2]”);
WebElement shippingAddressCheckbox=driver.findElement(By.id(“shippingaddress”);
WebElement shippingAddress=driver.findElement(By.id(“sh_地址”);
WebElement shippingCountry=driver.findElement(By.id(“sh_countryid”);
选择shippingCountryName=新选择(shippingCountry);
WebElement shippingState=driver.findElement(By.id(“sh_stateid”);
选择shippingStateName=新建选择(shippingState);
WebElement shippingCity=driver.findElement(By.id(“sh_cityid”);
选择shippingCityName=新建选择(shippingCity);
WebElement shippingZipCode=driver.findElement(By.id(“sh_邮政编码”);
WebElement shippingPhoneNumber=driver.findElement(By.id(“sh_phone”));
//通过保持所有字段为空并单击“保存”按钮添加客户页面验证检查
保存按钮。单击();
睡眠(1000);
//只需输入名字并单击“保存”按钮,即可添加客户页面验证检查
名字。sendKeys(“约翰”);
保存按钮。单击();
睡眠(500);
firstName.clear();
//通过只输入姓氏并单击“保存”按钮添加客户页面验证检查
lastName.sendKeys(“史密斯”);
保存按钮。单击();
睡眠(500);
lastName.clear();
//只需输入帐户电子邮件并单击“保存”按钮,即可添加客户页面验证检查
accountEmail.sendKeys(“john@gmail.com");
保存按钮。单击();
睡眠(500);
accountEmail.clear();
//仅选中“促销通讯”复选框并单击“保存”按钮,即可添加客户页面验证检查
复选框。单击();
保存按钮。单击();
睡眠(500);
复选框。单击();//取消选中复选框
//添加客户页面验证检查,只需在“出生日期”字段中输入出生日期,然后单击“保存”按钮
dateOfBirth.click();

对于(inti=0;i您已经给出了问题本身的答案,正如您所说的,异常在页面刷新后出现,因此基本上,该元素在DOM上不存在,可能js刷新是一个原因。 你可以参考下面的链接来获取详细信息

请阅读并提供您尝试过的代码和执行结果,包括任何错误消息等。在SO上提出一个好问题的一个要求是提供一个完整的答案。转储100行代码并询问错误不是一种合理或负责任的提问方式。您需要花一些时间在Google上搜索过时的代码消除异常,缩小代码中的实际问题,并尝试不同的解决方案