首页 > 解决方案 > python chromedirver 不会退出

问题描述

[我英语不好。敬请谅解。:)]

有时即使使用隐含超时,chrome 驱动程序也不会结束。

为了防止这种情况,我使用了 Windows 的 Timeout Decorator。

超时装饰器效果很好,

但是,Chrome 驱动程序并没有被关闭。

我还检查了它是否是同一个对象,但对象是相同的。

什么原因?

好像是在使用超时装饰器……(Chrome驱动也是最新版本)

self.driver.quit() <---- 这个方法有问题。

@timeout(10)
def driver_quit(self):
    self.driver.quit()

@timeout(120)
def driver_get(self, url):
    self.driver.get(url)


def call_url(self, url):
    try:
        self.driver_get(url)
    except Exception as e:
        try:
            self.driver_quit()
        except Exception as e:
            pass



def timeout(timeout):
    from threading import Thread
    import functools


    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))]
        def newFunc():
            try:
                res[0] = func(*args, **kwargs)
            except Exception as e:
                res[0] = e

        t = Thread(target=newFunc)
        t.daemon = True
        try:
            t.start()
            t.join(timeout)
        except Exception as je:
            print('error starting thread')
            raise je
        ret = res[0]
        if isinstance(ret, BaseException):
            raise ret
        return ret

    return wrapper

return deco

=============== 修改代码===============

WebDriverException 发生在最后,

但是 Chamedriver 关闭了这一行 ==> driver.close()。

def call_url(self, url):
    try:
        self.driver_get(url)
    except:
         try:
             self.driver_quit()
         except:
             pass
         finally:
             self.driver.close()
             self.driver.quit()

标签: python-3.xseleniumselenium-chromedriver

解决方案


一种解决方法是同时调用driver.quit()driver.close()

为此,您可以将命令放在finally:语句中。

您将使用 a 包装所有自动化,try:然后在最后except:使用该finally:语句。

try:
    # do my automated tasks
except:
    pass
finally:
    driver.close()
    driver.quit()

编辑

如果您发现这对您没有帮助,只需向 selenium 和 webdriver 维护人员报告错误。

希望这对你有帮助!


推荐阅读