完善_try_to_connect()逻辑

This commit is contained in:
g1879 2021-01-08 10:55:53 +08:00
parent 4d1b8e5109
commit f4e80fdd92
2 changed files with 32 additions and 14 deletions

View File

@ -100,26 +100,31 @@ class DriverPage(object):
:param show_errmsg: 是否抛出异常 :param show_errmsg: 是否抛出异常
:return: 是否成功 :return: 是否成功
""" """
err = None
def goto() -> bool: def go() -> bool:
nonlocal err
try: try:
self.driver.get(to_url) self.driver.get(to_url)
return True return True
except: except Exception as e:
err = e
return False return False
is_ok = self.check_page() if goto() else False is_ok = False
for _ in range(times + 1):
is_ok = self.check_page() if go() else False
for _ in range(times):
if is_ok is not False: if is_ok is not False:
break break
if _ < times:
sleep(interval) sleep(interval)
print(f'重试 {to_url}') print(f'重试 {to_url}')
is_ok = self.check_page() if goto() else False
if is_ok is False and show_errmsg: if is_ok is False and show_errmsg:
raise ConnectionError('Connect error.') raise err if err is not None else ConnectionError('Connect error.')
return is_ok return is_ok

View File

@ -197,15 +197,28 @@ class SessionPage(object):
:param kwargs: 连接参数 :param kwargs: 连接参数
:return: HTMLResponse对象 :return: HTMLResponse对象
""" """
r = self._make_response(to_url, mode=mode, show_errmsg=show_errmsg, **kwargs)[0] err = None
r = None
for _ in range(times): def go() -> Union[Response, None]:
if (r and r.content != b'') or (r is not None and r.status_code in (403, 404)): nonlocal err
try:
return self._make_response(to_url, mode=mode, show_errmsg=True, **kwargs)[0]
except Exception as e:
err = e
return None
for _ in range(times + 1):
r = go()
if r and (r.content != b'' or r.status_code in (403, 404)):
break break
print(f'重试 {to_url}') if _ < times:
sleep(interval) sleep(interval)
r = self._make_response(to_url, mode=mode, show_errmsg=show_errmsg, **kwargs)[0] print(f'重试 {to_url}')
if not r and show_errmsg:
raise err if err is not None else ConnectionError('Connect error.')
return r return r