优化浏览器策略

This commit is contained in:
liuwei
2025-05-16 09:12:38 +08:00
parent f85604b5de
commit 4db99a882a

View File

@@ -160,30 +160,57 @@ async def html_to_image(html_file, output_image):
"""
使用 Playwright 加载 HTML 文件并截图(异步)。
"""
async with async_playwright() as p:
possible_chrome_paths = [
r"C:\Users\Liu_WIN10\AppData\Local\Google\Chrome\Application\chrome.exe",
r"C:\Users\Liu-OPEN\AppData\Local\Google\Chrome\Application\chrome.exe",
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
]
browser_path = None
for path in possible_chrome_paths:
if os.path.exists(path):
browser_path = path
print(f"找到浏览器路径: {browser_path}")
break
if browser_path:
browser = await p.chromium.launch(executable_path=browser_path)
else:
print("未找到指定的Chrome浏览器路径使用默认浏览器")
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(f'file://{os.path.abspath(html_file)}')
await page.set_viewport_size({"width": 750, "height": 800})
await page.wait_for_timeout(500)
await page.screenshot(path=output_image, full_page=True)
await browser.close()
try:
async with async_playwright() as p:
# 检查系统类型
if os.name == 'nt': # Windows
possible_chrome_paths = [
r"C:\Users\Liu_WIN10\AppData\Local\Google\Chrome\Application\chrome.exe",
r"C:\Users\Liu-OPEN\AppData\Local\Google\Chrome\Application\chrome.exe",
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
]
browser_path = None
for path in possible_chrome_paths:
if os.path.exists(path):
browser_path = path
print(f"找到浏览器路径: {browser_path}")
break
if browser_path:
browser = await p.chromium.launch(executable_path=browser_path)
else:
print("未找到指定的Chrome浏览器路径尝试使用默认浏览器")
# 尝试安装 Playwright 浏览器
try:
import subprocess
print("正在安装 Playwright 浏览器...")
subprocess.run(["playwright", "install"], check=True)
print("Playwright 浏览器安装完成")
except Exception as install_error:
print(f"安装 Playwright 浏览器失败: {install_error}")
browser = await p.chromium.launch()
else: # Linux
try:
# 尝试安装 Playwright 浏览器
import subprocess
print("正在安装 Playwright 浏览器...")
subprocess.run(["playwright", "install"], check=True)
print("Playwright 浏览器安装完成")
except Exception as install_error:
print(f"安装 Playwright 浏览器失败: {install_error}")
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(f'file://{os.path.abspath(html_file)}')
await page.set_viewport_size({"width": 750, "height": 800})
await page.wait_for_timeout(500)
await page.screenshot(path=output_image, full_page=True)
await browser.close()
except Exception as e:
print(f"浏览器操作失败: {e}")
if "Executable doesn't exist" in str(e):
print("请运行 'playwright install' 命令安装必要的浏览器组件")
raise
# 主函数:从字符串转换 Markdown 到图片(异步版)