调整close_driver()和kill_browser()逻辑

This commit is contained in:
g1879 2022-01-06 16:52:40 +08:00
parent bae4687de2
commit 13dadf74a7
2 changed files with 18 additions and 7 deletions

View File

@ -185,11 +185,14 @@ class Drission(object):
pid = self.get_browser_progress_id()
from os import popen
if pid and popen(f'tasklist | findstr {pid}').read().lower().startswith('chrome.exe'):
print('kill')
from platform import system
if pid and system().lower() == 'windows' \
and popen(f'tasklist | findstr {pid}').read().lower().startswith('chrome.exe'):
popen(f'taskkill /pid {pid} /F')
else:
self.close_driver()
self._driver.quit()
def get_browser_progress_id(self) -> Union[str, None]:
"""获取浏览器进程id"""
@ -223,6 +226,10 @@ class Drission(object):
self._show_or_hide_browser(False)
def _show_or_hide_browser(self, hide: bool = True) -> None:
from platform import system
if system().lower() != 'windows':
raise OSError('该方法只能在Windows系统使用。')
try:
from win32gui import ShowWindow
from win32con import SW_HIDE, SW_SHOW
@ -360,10 +367,14 @@ class Drission(object):
selenium_user_agent = driver.execute_script("return navigator.userAgent;")
session.headers.update({"User-Agent": selenium_user_agent})
def close_driver(self) -> None:
def close_driver(self, kill: bool = False) -> None:
"""关闭driver和浏览器"""
if self._driver:
self._driver.quit()
if kill:
self.kill_browser()
else:
self._driver.quit()
self._driver = None
def close_session(self) -> None:

View File

@ -303,7 +303,7 @@ class MixPage(SessionPage, DriverPage, BasePage):
"""
self._drission.cookies_to_session(copy_user_agent)
def cookies_to_driver(self, url=None) -> None:
def cookies_to_driver(self, url: str = None) -> None:
"""从session复制cookies到driver \n
chrome需要指定域才能接收cookies \n
:param url: 目标域
@ -330,7 +330,7 @@ class MixPage(SessionPage, DriverPage, BasePage):
def close_driver(self) -> None:
"""关闭driver及浏览器"""
self._driver = None
self.drission.close_driver()
self.drission.close_driver(True)
def close_session(self) -> None:
"""关闭session"""