selenium优雅打开并关闭网页

  • with 上下文管理器
    • 在python中是这样介绍的所有实现了__enter__ __exit__ dunder method魔术方法的对象都可以用with
    • 接下来以Chrome为例查看底层
      def __enter__(self):
          return self
      
      def __exit__(self,
                     exc_type: typing.Optional[typing.Type[BaseException]],
                       exc: typing.Optional[BaseException],
                       traceback: typing.Optional[types.TracebackType]):
          self.quit()
  • 优雅打开并关闭 
    from selenium import webdriver
    with webdriver.Chrome('../chromedriver.exe') as dirver:
        dirver.get('https://www.baidu.com/')
        from time import sleep
        sleep(5)

     

 
posted @ 2023-07-10 13:40  手可摘星辰/*  阅读(39)  评论(0编辑  收藏  举报