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

时间:2017-05-02 07:43:59

标签: selenium-webdriver

当我尝试运行此代码时,我收到org.openqa.selenium.StaleElementReferenceException:在缓存中找不到元素 - 也许页面自查找以来已更改 命令持续时间或超时: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

    }

}

1 个答案:

答案 0 :(得分:0)

你已经给出了问题本身的答案,因为你说在页面刷新后出现异常,所以基本上,DOM上不存在该元素,可能是js刷新是一个原因。 您可以参考以下链接获取有关它的详细信息 http://www.seleniumhq.org/exceptions/stale_element_reference.jsp