From 866e93846831830dc3d38b835f03414fd24c530e Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 6 Nov 2025 17:23:58 +0800 Subject: [PATCH] =?UTF-8?q?2fa=E9=AA=8C=E8=AF=81=E8=BF=9B=E8=A1=8C?= =?UTF-8?q?=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spider/task.py | 71 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/spider/task.py b/spider/task.py index bbc1011..4024bf8 100644 --- a/spider/task.py +++ b/spider/task.py @@ -848,12 +848,73 @@ def get_proxy_from_api(): p = proxy_data.get("proxy") if p: return f"http://{p}" + else: + raise OperationFailed(f"获取代理时出错={proxy_data}") - raise OperationFailed(f"获取代理时出错={proxy_data}") + raise OperationFailed(f"获取代理时出错") except Exception as e: raise OperationFailed("获取代理时出错") from e +def login_with_2fa_retry(page, code_2fa, max_retries=3): + """ + 带重试机制的2FA登录 + """ + retry_count = 0 + + while retry_count < max_retries: + try: + print(f"第 {retry_count + 1} 次尝试2FA验证...") + + # 生成2FA验证码 + auth_code = pyotp.TOTP(code_2fa).now() + print(f"生成的2FA验证码: {auth_code}") + + # 输入验证码 + code_input = page.wait_for_selector( + 'input[aria-label="Code"][type="text"]', + timeout=60000 + ) + code_input.fill(auth_code) + + # 等待可能的验证结果 + page.wait_for_timeout(2000) # 等待2秒让系统处理 + + # 检查是否出现错误信息 + error_element = page.wait_for_selector( + 'span:has-text("This code doesn’t work. Check it’s correct or try a new one.")', timeout=10000) + + if error_element and error_element.is_visible(): + print("2FA验证码错误,准备重试...") + retry_count += 1 + + # 清空输入框重新输入 + code_input.fill("") + + # 如果不是最后一次重试,等待一段时间再重试 + if retry_count < max_retries: + wait_time = 5 # 等待5秒 + print(f"等待 {wait_time} 秒后重试...") + time.sleep(wait_time) + continue + else: + logger.info("2FA验证成功!") + return True + + except TimeoutError: + logger.info("查找输入框超时,可能是页面加载问题") + retry_count += 1 + if retry_count < max_retries: + time.sleep(3) + continue + except Exception as e: + logger.info(f"2FA验证发生未知错误: {e}") + retry_count += 1 + if retry_count < max_retries: + time.sleep(3) + continue + + def playwright_m_login(username, password, code_2fa=None): logger.info(f"登录账号{username}") # 检查是否冻结 @@ -943,9 +1004,11 @@ def playwright_m_login(username, password, code_2fa=None): page.wait_for_selector('span:has-text("Go to your authentication app")', timeout=60000) # 输入2faCode - auth_code = pyotp.TOTP(code_2fa).now() - page.wait_for_selector('input[aria-label="Code"][type="text"]', timeout=60000).fill(auth_code) - + try: + login_with_2fa_retry(page, code_2fa) + except Exception as e: + logger.error(f"2FA验证失败: {e}", exc_info=True) + raise OperationFailed(f"2FA验证失败: {e}") # 点击继续 page.query_selector('div[role="button"][aria-label="Continue"]').click()