[Python] Firefox handled by Selenium but keep instance running on script termination to...

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Selenium to handle the independent browser usage for Firefox from downloading (~/.cache/firefox) to starting and controlling it, but if my python script is terminated, the running Firefox instance is too.

    Because I use the script again and again, I need something like: Start Firefox in --marionette mode with debugging port open, if not already a running instance is detected. Like, the first run of the python script would start that Firefox instance handled by selenium (because Firefox isn't installed by default on systems who are running the script). But later reruns of the script would just connect to the already running instance.

    How can this be done with Selenium handling the driver and not by simply starting a popen subprocess?

    Currently, this is how I'm using Firefox by Selenium in my script:

    from selenium.webdriver.firefox.options import Options
    from selenium import webdriver

    from selenium.webdriver import Keys, ActionChains
    from selenium.webdriver.common.actions.action_builder import ActionBuilder
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    class Browser:
    firefox_options = Options()
    firefox_options.add_argument("-profile")
    firefox_options.add_argument("C:/firefox/profile/")
    driver = None

    wait = None
    EC = EC
    By = By
    Keys = Keys
    ActionChains = ActionChains
    ActionBuilder = ActionBuilder

    def __init__(self):
    try:
    self.driver = webdriver.Firefox(options=self.firefox_options)
    self.wait = WebDriverWait(self.driver, timeout=15, poll_frequency=.2)
    except:
    raise ValueError("Firefox not running?")

    Continue reading...

Compartilhe esta Página