0

You know how in Python, you can open files using a with open() clause, is it possible to open selenium drivers using that clause so that it automatically closes the driver when you're done? Remembering to close the drivers that I open is something that I often forget and I'm just wondering if there's a better way.

This is what I mean by with open clause.

with open([INSERT FILE NAME HERE], [INSERT ACCESS MODE HERE]) as fileName: [INSERT CODE]

54starr
  • 11
  • 1
  • Welcome to Stack Overflow. I don't quite follow. What would the "file name" and "mode" be, if you wanted to use a Selenium driver this way? What exactly does "opening" and "closing" them entail? – Karl Knechtel Jan 25 '23 at 19:58

1 Answers1

0

you would need context manager and code would be like

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
class MySeleniumContextMgr():
    def __init__(self):
        print("build a driver")
        self.driver=webdriver.Chrome(executable_path="./chromedriver")
         
    def __enter__(self):
        print("All coding logic")
        self.driver.get("https://simpleappdesigner.pythonanywhere.com/")
        time.sleep(10)
        return self
     
    def __exit__(self, exc_type, exc_value, exc_traceback):
        print("Driver on quit!")
        self.driver.quit()
with MySeleniumContextMgr() as mydriver:
    print("done")

so print would be

build a driver
All coding logic
done
Driver on quit!
simpleApp
  • 2,885
  • 2
  • 10
  • 19