To print the cookies returned by the login_attempt function for each captcha after submitting tasks to the ThreadPoolExecutor, you can follow a similar approach as before. You would retrieve each future's result and print it along with the associated captcha. Here's how you can achieve that:
Using concurrent.futures.as_completed()
This method processes results in the order they are completed:
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
print(f"Generating {len(captchas)} login attempts..")
# Submit tasks and create mapping of futures to their corresponding captcha
futures = {executor.submit(login_attempt, captcha): captcha for captcha in captchas}
# Loop through futures as they are completed
for future in concurrent.futures.as_completed(futures):
captcha = futures[future] # Get the captcha associated with this future
try:
cookie = future.result() # Get the result of the login_attempt
print(f'Captcha: {captcha}, Cookie: {cookie}') # Print the captcha and its corresponding cookie
except Exception as e:
print(f'Captcha: {captcha}, Exception: {e}') # Handle any exceptions that occurred
Using a simple loop
If you want to process results in the order they were submitted, you can do it like this:
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
print(f"Generating {len(captchas)} login attempts..")
# Submit tasks and create mapping of futures to their corresponding captcha
futures = {executor.submit(login_attempt, captcha): captcha for captcha in captchas}
for future in futures:
captcha = futures[future] # Get the captcha associated with this future
try:
cookie = future.result() # Get the result of the login_attempt
print(f'Captcha: {captcha}, Cookie: {cookie}') # Print the captcha and its corresponding cookie
except Exception as e:
print(f'Captcha: {captcha}, Exception: {e}') # Handle any exceptions that occurred
Explanation:
- Submitting Tasks: Each captcha's login attempt is submitted as a task, and the futures mapping captures the relationship between each future and its corresponding captcha.
- Retrieving Results: You either loop over the completed futures to process cookies as they complete or iterate through the futures in the order submitted. Both methods will fetch the result of
login_attempt via future.result().
- Printing Cookies: Upon retrieving the result, which in this case is a cookie, you can print it alongside its corresponding captcha. If an error occurs during the login attempt, it will be caught in the exception handling block.
This will allow you to see which captcha corresponds to which cookie, and also capture any exceptions thrown by the login_attempt function.