How can I navigate to multiple pages from the same driver and login sessions?

473 Views Asked by At

I am new to python and selenium and I got stuck somehow with this scenario:

I have a list of customer_ids and i need to verify in an admin some data;

The customer page can be composed: base_url/customers/customer_id. I wanted to know if it is possible to use the same session for iterating through the pages... The problem is that I need to login each and every time because each time driver.get(url) is called, a new driver instance appears and I am asked to login again...

In Java, there is driver.navigate() and you are able to access a new url from the same browser instance...

I have created this code:

    for customer in Customers.customers_list:
            url = Customers.base_url + "customers/" + customer
            
            options = webdriver.ChromeOptions()
            
            options.add_argument("--headless")
            
            driver = webdriver.Chrome(executable_path=credentials.Credentials.set_chrome_driver_path(), options=options)
            
            driver.get(url)
            username_input = driver.find_element(By.ID, "username")
            username_input.send_keys(credentials.Credentials.username)

            password_input = driver.find_element(By.ID, "password")
            password_input.send_keys(credentials.Credentials.password)

            submit_button = driver.find_element(By.XPATH, "//BUTTON[@type='submit'][text()='Log In']")
            submit_button.click()
            
            try:
                element = EC.text_to_be_present_in_element((By.XPATH, "//BUTTON[text()='Disable account ']"), "Disable")
                page_loaded = WebDriverWait(driver, 15).until(element)     
            except TimeoutException:
                print("page not loaded " + customer) 
            
            element_text = driver.find_element(By.XPATH, "//BUTTON[text()='Disable account ']").text

            if element_text != "Disable account":
                print("page not loaded " + customer)
1

There are 1 best solutions below

1
ketanvj On

@AlexQA, you can move the following lines in your code up and outside the for loop and it should work as you want it to be. This will open the browser only once.

options = webdriver.ChromeOptions()
       
options.add_argument("--headless")
        
driver = webdriver.Chrome(executable_path=credentials.Credentials.set_chrome_driver_path(), options=options)