[Tutor] Pass options in one line (Selenium)

Alan Gauld alan.gauld at yahoo.co.uk
Thu Oct 28 19:44:14 EDT 2021


On 28/10/2021 16:45, Julius Hamilton wrote:
> Hey,
> 
> Would anyone know how to do the following in fewer lines?
> 
> from selenium import webdriver
> from selenium.webdriver.firefox.options import Options
> 
> options = Options()

You could omit the import since you only use Options once.
So it becomes

options = selenium.webdriver.firefox.options.Options()


> options.headless = True
> driver = webdriver.Firefox(options = options)
> 
> Basically, I’d like to do this:
> 
> driver = webdriver.Firefox(options = Options().headless = True)

But you can't because you can't do an assignment inside a
function call. And you can't pass a Boolean conditional value
to the Firefox initializer for options. So you need to create
the options object, set its values and pass it in, just
as you are doing.

> But the only issue is trying to instantiate a class, then modify a
> property, and passing that as the argument to something else, all at once.

Why do you want to? There are no prizes for writing difficult
to debug code. And hiding the options object makes it impossible
for you to access it and find out its settings. Why would you
want to do that?

There are no prizes for writing the shortest code. Write clear
and easy to understand code and your maintainers (who may be
you in 6 months) will thank you for it.

> Maybe Options(self.headless = True)?

You can only pass the parameters that are defined for the function
The option.__init__() does not have a parameter called self.headless.

Now, if you really, really want to do this you can, using a class.
But it adds more lines not less. You can define your own options class
derived from the selenium one and provide a headless parameter.

class HeadlessOptions(Options):
   def __init__(self, headless=True, *args, **kwargs):
       Options.__init__(self, *args,**args)
       self.headless = headless

Now you can create Firefox with

driver = webdriver.Firefox(options = HeadlessOptions())

But while saving the Options creation and assignment you now
have a class definition... Which version is easier to maintain
I'll leave as a moot point. Personally I'd go for the original
unless you have a lot of similar programs to write in which
case stick your class in a module so you can reuse it...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list