0

Here's my code in a simplified way:

from selenium import webdriver

driver = webdriver.Firefox(executable_path=r"F:\geckodriver.exe")

class Acesso():
    def __init__(self):
        driver.get(link)

    def scroll():
        # Function
    driver.click()

    def url():
        # driver.get("https://google.com")

Acesso()

Writing it this way makes the browser to open up as soon as I define my driver variable. Is there any way I can define the webdriver.Firefox() without automatically opening the browser? My goal here is that I want to define the driver variable inside my __init__ function so I can pass an argument to it. Something like this:

def __init__(self, agent):
    self.agent = agent
    driver = webdriver.Firefox(executable_path=r"F:\geckodriver.exe",firefox_profile=agent)

My issue is that writing it this way I can't use the driver variable in other functions and if I define the variable for each function the browser will open automatically at any function's call. Any solutions?

  • Does this answer your question? [How to make Firefox headless programmatically in Selenium with Python?](https://stackoverflow.com/questions/46753393/how-to-make-firefox-headless-programmatically-in-selenium-with-python) – Alexandru Cristiean Jun 28 '21 at 16:40
  • No, I don't want the headless Firefox, I just want to define my `drive` without opening automatically. Example: `letter = a`. Here it's just defined, it doesn't do anything. That's what I want with the `driver` variable. Any tips? – bona.coder Jun 28 '21 at 16:45

3 Answers3

0

Try this: Create the driver variable but initialize it to None.

Then, in each function that uses it, check if it's None and if it is, then set it to Firefox(...) -- if it's not None, assume it's already set to the Firefox browser and proceed that way.

Then the browser should open the first function and stay open/be reused for the rest.

Leah F
  • 1
0
from selenium import webdriver

try:
    fireFoxOptions = webdriver.FirefoxOptions()
    fireFoxOptions.set_headless()
    brower = webdriver.Firefox(firefox_options=fireFoxOptions, executable_path=r"F:\geckodriver.exe")
Gwenael
  • 66
  • 3
0

Found a solution setting the driver variable as global. Now I can define inside my function and still use it on other functions.