我正在编写一个Python代码,其中我需要在一个类中使用Selenium Webbrowser。我希望硒会话在退出python时能正确完成
我将webbrowser变量保存为类的字段。为了退出会话,我决定在我班上的quit()
方法内调用webbrowser的__del__()
方法,但是没有用:
from selenium import webdriver
from sys import stderr
class MyClass:
def __init__(self):
opts = webdriver.chrome.options.Options()
opts.add_argument('--headless')
opts.add_argument('--no-sandbox')
opts.add_argument('--disable-dev-shm-usage')
assert opts.headless
self.browser = webdriver.Chrome(options=opts)
def __del__(self):
self.browser.quit()
stderr.write("Browser has been closed correctly!\n")
# Other methods of my class
if __name__ == "__main__":
a = MyClass()
如果现在我调用类似del a
之类的信息,则会收到Browser has been closed correctly!
消息,并且chromedriver
从正在运行的进程列表中消失。但是,如果退出python,则会收到错误消息:
Exception ignored in: <bound method MyClass.__del__ of <__main__.MyClass object at 0x7f37eb918898>>
Traceback (most recent call last):
File "<stdin>", line 11, in __del__
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 158, in quit
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/common/service.py", line 151, in stop
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/common/service.py", line 122, in send_remote_shutdown_command
ImportError: sys.meta_path is None, Python is likely shutting down
答案 0 :(得分:1)
其他两个选择:
MyClass
用作context manager。在其__exit__
方法中,退出浏览器。然后使用with MyClass() as mc...
,其中__exit__
将在块结束后被调用atexit
(我称之为过大杀伤力)-将MyClass
的实例注册到模块的作用域;注册一个退出函数,该退出函数在程序退出时为每个已注册的实例调用obj.browser.quit()
。