L
L
lcd12322016-04-01 02:27:14
Python
lcd1232, 2016-04-01 02:27:14

Is it possible to use the with as construct on selenium?

Is this code equivalent to:

browser = webdriver.Firefox()
browser.get('http://www.google.com')
browser.save_screenshot('screenie.png')
browser.quit()

This?
with webdriver.Firefox() as browser:
  browser.get('http://www.google.com')
  browser.save_screenshot('screenie.png')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2016-04-01
@abcd0x00

To determine if the with statement can be used with the obj object, you just need to execute obj.__enter__.
If there is a method, then it is possible.
That's an example:

>>> f = open('/etc/passwd')
>>> f.__enter__
<built-in method __enter__ of _io.TextIOWrapper object at 0xb750e644>
>>>

D
Danil Biryukov-Romanov, 2016-04-01
@urtow

In [1]: from selenium import webdriver
In [2]: bro = webdriver.Firefox()
In [3]: bro.__enter__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-d8c2812442f0> in <module>()
----> 1 bro.__enter__
AttributeError: 'WebDriver' object has no attribute '__enter__'

No.
But, we can write a wrapper that implements this functionality ourselves. with .. as uses two magic methods __enter__ and __exit__
Described here: https://www.python.org/dev/peps/pep-0343/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question