Skip to content

Instantly share code, notes, and snippets.

@stevenctl
Created March 21, 2019 06:16
Show Gist options
  • Save stevenctl/d34e0494843479b2a12b9e58cf8d645e to your computer and use it in GitHub Desktop.
Save stevenctl/d34e0494843479b2a12b9e58cf8d645e to your computer and use it in GitHub Desktop.
Python Selenium Reusable Browser Session
# Sometimes I have some tedious thing to do like data entry
# Sometimes I script that tedious thing using selenium
# Sometimes I have to login to something to enter that data
# This allows you to rerun your script using the same session
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
SELENIUM_SESSION_FILE = './selenium_session'
SELENIUM_PORT=9515
def build_driver():
options = Options()
options.add_argument("--disable-infobars")
options.add_argument("--enable-file-cookies")
if os.path.isfile(SELENIUM_SESSION_FILE):
session_file = open(SELENIUM_SESSION_FILE)
session_info = session_file.readlines()
session_file.close()
executor_url = session_info[0].strip()
session_id = session_info[1].strip()
capabilities = options.to_capabilities()
driver = webdriver.Remote(command_executor=executor_url, desired_capabilities=capabilities)
# prevent annoying empty chrome windows
driver.close()
driver.quit()
# attach to existing session
driver.session_id = session_id
return driver
driver = webdriver.Chrome(options=options, port=SELENIUM_PORT)
session_file = open(SELENIUM_SESSION_FILE, 'w')
session_file.writelines([
driver.command_executor._url,
"\n",
driver.session_id,
"\n",
])
session_file.close()
return driver
driver = build_driver()
driver.get("https://google.com/")
# write whatever automated thing you need to do
# if you plan to re-run be sure that the actions are idempotent
@SiddhiDe
Copy link

Thank you for the solution. This works for me the first time. But when I try to run the script again I get a "Failed to establish a new connection: [Errno 61] Connection refused" error. I'm not able to find a solution to fix this. Is there something I'm missing?

@stevenctl
Copy link
Author

It's been a while since I've used this, but you might want to delete the selenium_session file if this is happening if you're tearing down completely on re-runs.

The point of that file is so you can resume without starting over.

@SiddhiDe
Copy link

Thank you for your response, Steven. I did the same and it worked perfectly. This code has been extremely helpful.

@ahait
Copy link

ahait commented Nov 24, 2022

When you "hijack" a session like that, when you want to close it in the end by "driver.quit()" - the chromedriver process is not killed, only the chrome. How can you make sure the chromedriver process is killed as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment