控制tabs减少用get()方式,提高稳定性

This commit is contained in:
g1879 2023-11-02 23:06:29 +08:00
parent e8f3cf8df3
commit 2a0fa73f9d
3 changed files with 8 additions and 16 deletions

View File

@ -79,12 +79,13 @@ class Browser(object):
@property
def tabs_count(self):
"""返回标签页数量"""
return len(self.tabs)
j = self.run_cdp('Target.getTargets')['targetInfos'] # 不要改用get避免卡死
return len([i for i in j if i['type'] == 'page'])
@property
def tabs(self):
"""返回所有标签页id组成的列表"""
j = self._driver.get(f'http://{self.address}/json').json() # 不要改用cdp
j = self._driver.get(f'http://{self.address}/json').json() # 不要改用cdp,因为顺序不对
return [i['id'] for i in j if i['type'] == 'page']
@property
@ -118,14 +119,14 @@ class Browser(object):
:param tab_id: 标签页id
:return: None
"""
self._driver.get(f'http://{self.address}/json/close/{tab_id}')
self.run_cdp('Target.closeTarget', targetId=tab_id)
def activate_tab(self, tab_id):
"""使标签页变为活动状态
:param tab_id: 标签页id
:return: None
"""
self._driver.get(f'http://{self.address}/json/activate/{tab_id}')
self.run_cdp('Target.activateTarget', targetId=tab_id)
def get_window_bounds(self, tab_id=None):
"""返回浏览器窗口位置和大小信息

View File

@ -91,7 +91,7 @@ class ChromiumFrame(ChromiumBase):
try:
super()._driver_init(tab_id)
except:
get(f'http://{self.address}/json', headers={'Connection': 'close'})
self.browser.driver.get(f'http://{self.address}/json')
super()._driver_init(tab_id)
self.driver.set_listener('Inspector.detached', self._onInspectorDetached)

View File

@ -161,17 +161,8 @@ class ChromiumPage(ChromiumBase):
:return: 新标签页的id
"""
if switch_to:
begin_tabs = set(self.tabs)
len_tabs = len(begin_tabs)
tid = self.run_cdp('Target.createTarget', url='')['targetId']
tabs = self.tabs
while len(tabs) == len_tabs:
tabs = self.tabs
sleep(.005)
new_tab = set(tabs) - begin_tabs
self._to_tab(new_tab.pop(), read_doc=False)
self._to_tab(tid, read_doc=False)
if url:
self.get(url)
@ -265,7 +256,7 @@ class ChromiumPage(ChromiumBase):
for tab in tabs:
self.browser.close_tab(tab)
sleep(.2)
while len(self.tabs) != end_len:
while self.tabs_count != end_len:
sleep(.1)
if self._main_tab in tabs: