File size: 2,232 Bytes
ea4ccbd a42ebc7 ea4ccbd a42ebc7 ea4ccbd a42ebc7 ea4ccbd a42ebc7 ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a ea4ccbd e8b8f2a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import gradio as gr
from playwright.sync_api import sync_playwright
from PIL import Image
import io
import subprocess
import sys
import os
# ==================== 自动安装浏览器 ====================
def install_browsers():
print("Downloading Playwright browsers...")
try:
subprocess.run(["playwright", "install", "chromium", "--with-deps"], check=True)
print("Browser installation completed!")
except Exception as e:
print(f"Browser install failed: {e}")
if "SPACE_ID" in os.environ: # HF Space 环境
install_browsers()
# ==================== 主函数 ====================
def run_automation(url: str, action: str = "screenshot"):
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(viewport={"width": 1280, "height": 720})
page.goto(url, wait_until="networkidle", timeout=60000)
if action == "screenshot":
screenshot_bytes = page.screenshot(full_page=True)
browser.close()
image = Image.open(io.BytesIO(screenshot_bytes))
return "✅ 截图成功!", image
else:
title = page.title()
browser.close()
return f"📄 页面标题:{title}", None
except Exception as e:
return f"❌ 错误:{str(e)}", None
# ==================== Gradio 界面 ====================
with gr.Blocks(title="网页截图工具") as demo:
gr.Markdown("# 🌐 网页自动化演示(Playwright)")
with gr.Row():
url_input = gr.Textbox(
label="网址",
placeholder="https://huggingface.co",
value="https://example.com",
scale=4
)
action = gr.Radio(["screenshot", "title"], label="操作", value="screenshot")
btn = gr.Button("🚀 执行", variant="primary")
with gr.Row():
output_text = gr.Textbox(label="状态")
output_image = gr.Image(label="截图结果")
btn.click(
fn=run_automation,
inputs=[url_input, action],
outputs=[output_text, output_image]
)
demo.launch() |