优化浏览器策略

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 文件并截图(异步)。 使用 Playwright 加载 HTML 文件并截图(异步)。
""" """
async with async_playwright() as p: try:
possible_chrome_paths = [ async with async_playwright() as p:
r"C:\Users\Liu_WIN10\AppData\Local\Google\Chrome\Application\chrome.exe", # 检查系统类型
r"C:\Users\Liu-OPEN\AppData\Local\Google\Chrome\Application\chrome.exe", if os.name == 'nt': # Windows
r"C:\Program Files\Google\Chrome\Application\chrome.exe", possible_chrome_paths = [
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" r"C:\Users\Liu_WIN10\AppData\Local\Google\Chrome\Application\chrome.exe",
] r"C:\Users\Liu-OPEN\AppData\Local\Google\Chrome\Application\chrome.exe",
browser_path = None r"C:\Program Files\Google\Chrome\Application\chrome.exe",
for path in possible_chrome_paths: r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
if os.path.exists(path): ]
browser_path = path browser_path = None
print(f"找到浏览器路径: {browser_path}") for path in possible_chrome_paths:
break if os.path.exists(path):
if browser_path: browser_path = path
browser = await p.chromium.launch(executable_path=browser_path) print(f"找到浏览器路径: {browser_path}")
else: break
print("未找到指定的Chrome浏览器路径使用默认浏览器") if browser_path:
browser = await p.chromium.launch() browser = await p.chromium.launch(executable_path=browser_path)
page = await browser.new_page() else:
await page.goto(f'file://{os.path.abspath(html_file)}') print("未找到指定的Chrome浏览器路径尝试使用默认浏览器")
await page.set_viewport_size({"width": 750, "height": 800}) # 尝试安装 Playwright 浏览器
await page.wait_for_timeout(500) try:
await page.screenshot(path=output_image, full_page=True) import subprocess
await browser.close() 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 到图片(异步版) # 主函数:从字符串转换 Markdown 到图片(异步版)