使用PyInstaller打包后Python爬虫程序运行卡顿问题求助
问题排查与解决办法
1. 彻底清理PlayWright进程
打包后PlayWright的浏览器进程可能没完全退出,导致资源阻塞,别只靠page.close(),要把整个浏览器上下文关掉:
# 异步模式 await browser.close() # 同步模式直接调用 browser.close()
如果还是有残留进程,手动杀掉对应浏览器进程:
import psutil for proc in psutil.process_iter(['name']): # 对应你用的浏览器,比如chrome/msedge if proc.info['name'] in ['chrome.exe', 'msedge.exe']: try: proc.kill() except: pass
2. 把爬取逻辑放到独立线程,避免阻塞UI
Tkinter是单线程的,同步执行login会卡死UI线程,导致按钮文本根本更新不了。把爬取和分析逻辑丢到线程里:
import threading def run_task(): # 先执行登录 login_result = login() # 登录成功再触发分析 if login_result: # 必须用after回到UI线程更新按钮文本 root.after(0, lambda: button.config(text="Analyzing report...")) begin_report(login_result) # 按钮点击事件改成启动线程 button.config(command=lambda: threading.Thread(target=run_task, daemon=True).start())
3. 打包时补全PlayWright资源
PyInstaller打包可能没把PlayWright的浏览器二进制文件带上,导致exe运行时加载失败卡住。打包命令里加上资源路径:
# 替换成你本地的PlayWright浏览器路径,比如chromium的路径 pyinstaller --onefile --add-data "C:\Users\你的用户名\AppData\Local\ms-playwright\chromium-xxx\chrome-win\chrome.exe;." your_script.py
另外,打包时加上--console参数,运行exe别双击,用cmd打开,看控制台输出的错误信息,比如有没有缺依赖、登录时的网络错误。
4. 给login加异常捕获,排查是否卡在登录环节
exe运行时可能login过程中出了错但没提示,导致程序停在login,根本没走到begin_report。给login加异常日志:
def login(): try: # 原登录逻辑 report_content = ... return report_content except Exception as e: with open("error_log.txt", "w") as f: f.write(str(e)) # 回到UI线程提示错误 root.after(0, lambda: button.config(text="Login failed")) return None
内容的提问来源于stack exchange,提问作者wheat_thin_wiens
相关产品推荐
相关产品推荐

