File tree Expand file tree Collapse file tree 1 file changed +18
-3
lines changed
Expand file tree Collapse file tree 1 file changed +18
-3
lines changed Original file line number Diff line number Diff line change @@ -237,28 +237,43 @@ def _quit(driver):
237237
238238
239239class SafeDriver :
240+ """
241+ 包装交给上下文管理
242+ """
243+
240244 def __init__ (self , url , debug = False ):
241245 self .driver = selenium_driver (url , debug )
242246
243247 def __enter__ (self ):
244- return self
248+ return self . driver
245249
246250 def __exit__ (self , exc_type , exc_val , exc_tb ):
251+ """
252+ 使用with的时候触发
253+ :param exc_type:
254+ :param exc_val:
255+ :param exc_tb:
256+ :return:
257+ """
247258 if self .driver :
248259 _quit (self .driver )
249260
250261 def __del__ (self ):
262+ """
263+ 不使用with的时候触发
264+ :return:
265+ """
251266 if self .driver :
252267 _quit (self .driver )
253268
254269
255270if __name__ == '__main__' :
256271 # download_taobao_chromedriver()
257272 # download_chromedriver()
258- safe_driver = SafeDriver ("" )
273+ safe_driver = SafeDriver ("" ) # 触发__del__
259274 # 仅仅从功能上来说,instance 变量与safe_driver变量完全一样
260275 # 所不同的是,使用with启用上下文管理器以后,在退出缩进的时候会执行__exit__中的内容。
261- with SafeDriver ("" ) as instance :
276+ with SafeDriver ("" ) as instance : # 触发__exit__
262277 pass
263278 with safe_driver .driver as driver :
264279 pass
You can’t perform that action at this time.
0 commit comments