Python多线程启动循环后主流程未执行后续Selenium逻辑提前退出
问题原因
你遇到的提前退出问题,核心是代码缩进错误+线程逻辑缺失导致的,具体拆解:
- 缩进错误导致线程函数无实际逻辑
你给出的代码里,creator函数只定义了邮箱、密码这类基础变量,后续的请求注册的try-except块缩进回到了全局作用域,根本没被包裹进线程函数里。也就是说每个子线程启动后,跑完变量定义就直接返回,核心注册逻辑完全没在线程中运行。 - 全局try-except吞掉了初始化错误
那段缩进错误的try-except会在全局初始化阶段先执行,里面用到的requests.Session、请求参数都是creator的局部变量,全局作用域根本访问不到,直接触发NameError,被你写的except: pass静默吞掉,没有任何报错。 - 后续代码缩进/语法混乱
你精简的代码里出现了@type='text']")这类非法语法行,如果实际运行的代码存在这类问题,解释器会直接编译报错;如果是精简时的失误,还要检查Selenium相关代码是否被误缩进到循环、分支内部,导致执行不到。 - 排查误设守护线程的问题
如果你初始化线程的时候手动加过daemon=True,主线程会在执行完自身代码后立刻退出,但你说循环后的代码根本没执行,所以这个不是直接原因,也可以排查下是否误加了这个参数:threading.Thread(target=creator, daemon=True).start()这类写法会把线程设为守护线程。
修复方案
首先修正所有缩进,把注册逻辑正确包裹进creator函数,再把Selenium代码放到正确的全局作用域位置,参考写法:
import threading import requests import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 补全你缺失的全局变量 created = 0 errors = 0 monthnumber = 1 # 替换为你实际的月份逻辑 # 请确保 randomName、randomPassword、names、proxy1、PROXY、chrome_options 都正确定义 def creator(): global created, errors s = requests.session() email = randomName() password = randomPassword() name = names.get_full_name() data = { "displayname": name, "creation_point": "https://login.app.igloo.com?utm_source", "birth_month": monthnumber, "email": email + "@gmail.com", "password": password, } # 把请求逻辑正确缩进进线程函数内部 try: r = s.post( "https://spclient.wg.igloo.com/signup/public/v1/account/", data=data, proxies=proxy1.FormatProxy() ) if '{"status":1,"' in r.text: with open("creatediglooaccountsgen.txt", "a+") as f: f.write(email + "@gmail.com:" + password + ":" + PROXY + "\n") created += 1 else: errors += 1 except Exception as e: print(f"注册线程执行异常: {str(e)}") print("DONE") if __name__ == "__main__": maxthreads = 4 num = 0 threads = [] while num < maxthreads: num += 1 t = threading.Thread(target=creator) t.start() threads.append(t) # 如果你需要等所有注册线程跑完再执行登录,就加下面的join # 不需要等的话直接注释掉这两行 for t in threads: t.join() # 以下Selenium代码确保在主逻辑块内,缩进正确 chrome = webdriver.Chrome(options=chrome_options) chrome.get("https://igloo.com/en/login") with open('creatediglooaccountsgen.txt') as f: credentials = [x.strip().split(':', 1) for x in f if x.strip()] for username, password in credentials: chrome.find_element(By.ID, "login-username").send_keys(username) chrome.find_element(By.ID, "login-password").send_keys(password) try: WebDriverWait(chrome, 20).until( EC.element_to_be_clickable((By.XPATH, "//button[text()='Log In']")) ).click() except: print('登录按钮点击异常') time.sleep(3) chrome.close()
补充注意点
- 不要使用裸
except: pass,会把所有报错都吞掉,建议至少打印异常信息方便排查 - 函数内修改全局变量需要加
global声明,否则会被当成局部变量赋值报错 - Selenium的旧版
find_element_by_id这类方法已经被废弃,建议用find_element(By.ID, xxx)的新写法 - 如果你不需要等待4个注册线程执行完,直接跑Selenium的登录逻辑,去掉
join的循环即可,主线程会自动往下执行,不会提前退出
内容的提问来源于stack exchange,提问作者jaffa12
相关产品推荐
相关产品推荐

