Invalid Session Id running chromeDriver in loop Java

Issue

I am trying to run my webdriver in a loop which will close the window then reopen everytime it increments, but I keep getting an invalid session ID after it runs once. I looked into it and from what I have read it looks as if I have the webdriver set up correct in the loops. Below is my code in which open chrome is where I believe the error would be caused.

for(int i = 0; i < count; i++) {
            
            //Initiating your chromedriver
            openChrome();
            
            selectCountry();
            //DOB
            dob();
            
            
            nextPage();
            
            //name page
            namePage();
            
            nextPage();
            
            //email
            email();
            
            //phone number and verification code
            enterPhone();
            
            //accept terms
            acceptTerms();
            
            nextPage();
            
            //set Password
            enterPassword();
            
            nextPage();
            
            //bypass battletag
            Thread.sleep(2000);
            nextPage();
            
            result = result + "\r\n" + "Email: " + baseEmail + " ; " + "Password: " + password;
            
            
            driver.close();
            

        }
    public static void openChrome() {
        //setting the driver executable

        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\chromedriver.exe");
        
        if(counter > 0) {
            driver = new ChromeDriver();
        }
        
        
        //Applied wait time
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //maximize window
        driver.manage().window().maximize();

        //open browser with desried URL
        driver.get("https://account.battle.net/creation/flow/creation-full");
        
        counter++;
    }

Solution

You have not instantiate browser specific driver in openChrome() method :

Code :

public static void openChrome() {
        //setting the driver executable
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\chromedriver.exe");
         WebDriver driver = new ChromeDriver();
        //Applied wait time
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //maximize window
        driver.manage().window().maximize();

        //open browser with desried URL
        driver.get("https://account.battle.net/creation/flow/creation-full");
        
        
    } 

Answered By – cruisepandey

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published