Home > Net >  How can I access the same website twice without losing the settings, using Selenium?
How can I access the same website twice without losing the settings, using Selenium?

Time:06-26

I access a website, login and then instead of going through the process of finding and writing into the website's search field, I thought I'd simply re-access the website through a URL with the search query I want.

The problem is that when I access the website with the second "driver.get" (last line of code in the code below), it's as though it forgets that I logged in previously; as though it was a totally new session that I opened.

I have this code structure:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

path = Service("C://chromedriver.exe")
driver = webdriver.Chrome(service=path)

driver.get('https://testwebsite.com/')

login_email_button = driver.find_element(By.XPATH,'XXXXX')
login_email_button.click()

username = driver.find_element(By.ID, 'email')
password = driver.find_element(By.ID, 'password')

username.send_keys('myuser')
password.send_keys('mypassword')

driver.get('https://testwebsite.com/search?=televisions')

CodePudding user response:

when you do

driver.get('https://testwebsite.com/search?=televisions')

you're opening new session with no cookie or data of previous session. You can try to duplicate tab instead, to keep you logged in. You can do with:

Driver.execute_script

url = driver.current_url
driver.execute_script(f"window.open('{url}');") 
driver.switch_to.window(window_handles[1]) 

# if you want give a name to tab, pass it as second param like
driver.execute_script(f"window.open('{url}', 'second_tab_name');")
driver.switch_to.window('second_tab_name')

remember to use the switch if you want go back to the main tab

  • Related