Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use webdriver as context manager

I'm trying to use ChromeDriver within with block to make the code look better and get rid of using driver.quit() command in the end. However, It doesn't seem to work. As soon as the browser opens, it throws the following error. Perhaps, I doing something wrong. Ain't there any way to do so? Thanks in advance.

This is what I've tried:

from selenium import webdriver

with webdriver.Chrome() as wd:
    res = wd.get('https://stackoverflow.com/questions/')
    print(res.page_source)

#Another failure attempt with the same error

with webdriver.Chrome() as wd:
    wd.get('https://stackoverflow.com/questions/')
    print(wd.page_source)

This is the error I'm having:

    with webdriver.Chrome() as wd:
AttributeError: __exit__
like image 822
SIM Avatar asked Feb 05 '18 10:02

SIM


2 Answers

Now it's added to selenium (SeleniumHQ/selenium#5919) so you can simply use the original approach from your question:

from selenium import webdriver

with webdriver.Chrome() as wd:
    res = wd.get('https://stackoverflow.com/questions/')
    print(res.page_source)
like image 139
Ankor Avatar answered Nov 19 '22 04:11

Ankor


Try below solution and let me know in case it's not what you want:

from selenium import webdriver

class WebDriver:
    def __init__(self, driver):
        self.driver = driver

    def __enter__(self):
        return self.driver

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.driver.quit()


with WebDriver(webdriver.Chrome()) as wd:
    wd.get('https://stackoverflow.com/questions/')
    print(wd.page_source)
like image 12
Andersson Avatar answered Nov 19 '22 06:11

Andersson