P2P / init_playwright.py
ASC8384's picture
info
51687f7
raw
history blame
1.85 kB
#!/usr/bin/env python3
"""
Playwright初始化脚本
确保浏览器正确安装和配置
"""
import subprocess
import sys
import os
def check_playwright_installation():
"""检查playwright是否正确安装"""
try:
# 尝试导入playwright
from playwright.sync_api import sync_playwright
# 尝试启动浏览器
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
browser.close()
print("✅ Playwright 浏览器检查通过!")
return True
except Exception as e:
print(f"❌ Playwright 浏览器检查失败: {e}")
return False
def install_browsers():
"""安装playwright浏览器"""
try:
print("🔄 正在安装 Playwright 浏览器...")
subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"],
check=True)
subprocess.run([sys.executable, "-m", "playwright", "install-deps", "chromium"],
check=True)
print("✅ Playwright 浏览器安装完成!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ 浏览器安装失败: {e}")
return False
def main():
"""主函数"""
print("🚀 初始化 Playwright...")
# 首先检查是否已正确安装
if check_playwright_installation():
return True
# 如果检查失败,尝试重新安装
print("🔧 检测到问题,正在重新安装浏览器...")
if install_browsers():
# 重新检查
return check_playwright_installation()
return False
if __name__ == "__main__":
success = main()
if not success:
print("❌ Playwright 初始化失败!")
sys.exit(1)
print("🎉 Playwright 初始化成功!")