How can I use selenium options when a class is inherited from (webderiver.Firefox)

Question:

Simple using of options in python selenium is easy:

options = webdriver.FirefoxOptions()
options.headless=True

driver = webdriver.Firefox(options=options)

driver.get('https://lxml.de')
print(driver.title)

This is the code I understand.
My question is how to use options with OOP when a class has an inheritance from (webdriver.Firefox).
Like in this code:

class Get_selenium_dynamic_data(webdriver.Firefox):
    

    def __init__(self, teardown=True):

        self.teardown = teardown
        super(Get_selenium_dynamic_data, self).__init__()

        self.implicitly_wait(10)
        self.maximize_window() 

Obviously things like these don’t work:

options = webdriver.FirefoxOptions()
options.headless=True
class Get_selenium_dynamic_data(webdriver.Firefox(options=options)):

neither this one:

class Get_selenium_dynamic_data(webdriver.Firefox):
    def __init__(self, teardown=True):
        options = webdriver.FirefoxOptions()
        options.headless=True
        self(option=options)
        #self = self(option=options)
Asked By: Dmitriy Neledva

||

Answers:

You can add an argument

class Get_selenium_dynamic_data(webdriver.Firefox):
    def __init__(self, teardown=True, options=None):
        self.options = options

and then create an instance

driver = Get_selenium_dynamic_data(options=webdriver.FirefoxOptions())
Answered By: Curious koala

This question has nothing to do with selenium and applies to OOP’s inheritance mechanic only.
When an instance is initiated like this driver = webdriver.Firefox(options=options) webdriver.Firefox‘s __init__ takes the passed options argument and writes it to the instance’s namespace.

But, if there is new Get_selenium_dynamic_data class that has __init__ of its own then webdriver.Firefox‘s __init__ is going to be rewritten, and there would be no tool to write the options object to the instance namespace in a proper way.

So the solution to the problem is easy and trivial: we need to just take a piece of the webriver.Firefox‘s __init__ that works with options and reuse it in Get_selenium_dynamic_data. The best way to do in is super() function.

Final working code looks like this:

class Get_selenium_dynamic_data(webdriver.Firefox):
    
    def __init__(self, teardown=True, headless=False):

        if headless:
            opt = Options()
            opt.headless = True
            super(Get_selenium_dynamic_data, self).__init__(options=opt)

We can initiate an instance like this:

with Get_selenium_dynamic_data(headless=True) as driver:
with headless as boolean argument.

Answered By: Dmitriy Neledva
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.