Issue
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)
Solution
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 Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.