Description
def solve_captcha_with_retries(driver, max_attempts=5, min_successful=2):
solver = TwoCaptcha(API_KEY)
successful_solves = 0
attempt = 0
while attempt < max_attempts and successful_solves < min_successful:
try:
captcha_img_src = driver.find_element(By.ID, "captcha").get_attribute("src")
response = requests.get(captcha_img_src)
if response.status_code == 200:
with open('captcha.jpg', 'wb') as file:
file.write(response.content)
captcha_result = solver.normal('captcha.jpg')
if 'code' in captcha_result:
captcha_solution = captcha_result['code']
captcha_input = driver.find_element(By.NAME, "answer")
captcha_input.clear() # Ensure the input field is empty before entering the solution
captcha_input.send_keys(captcha_solution)
os.remove('captcha.jpg')
successful_solves += 1
if successful_solves >= min_successful:
logging.info(f"CAPTCHA solved successfully {successful_solves} times.")
return True
else:
logging.error(f"Captcha result did not contain 'code': {captcha_result}")
else:
logging.info(f"Attempt {attempt + 1}: Failed to download CAPTCHA image. Retrying...")
except Exception as e:
logging.error(f"Attempt {attempt + 1}: Error solving CAPTCHA: {e}")
finally:
attempt += 1
if successful_solves < min_successful:
logging.error("Failed to achieve the minimum number of successful CAPTCHA solves.")
return False
return True