如何使用 webdriver 作为上下文管理器 [英] How to use webdriver as context manager

查看:31
本文介绍了如何使用 webdriver 作为上下文管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 with 块中使用 ChromeDriver 来使代码看起来更好,并最终摆脱使用 driver.quit() 命令.但是,它似乎不起作用.浏览器一打开,就会抛出以下错误.也许,我做错了什么.就没有办法这样做吗?提前致谢.

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.

这是我试过的:

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)

这是我遇到的错误:

    with webdriver.Chrome() as wd:
AttributeError: __exit__

推荐答案

尝试以下解决方案,如果不是您想要的,请告诉我:

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)

这篇关于如何使用 webdriver 作为上下文管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆