import json
import os
import re
from playwright.sync_api import sync_playwright
#pip install playwright
#playwright install chromium
# 配置项
BASE_URL = "http://localhost:8080/#/"
# pages.json 的路径 (由于脚本在 截图 文件夹下,所以使用相对路径或绝对路径)
PAGES_JSON_PATH = r"e:\web\danzi\_____\pages.json"
# 截图输出目录(当前文件夹)
OUTPUT_DIR = os.path.dirname(os.path.abspath(__file__))

def clean_json_string(json_str):
    """
    清理 JSON 字符串中的单行和多行注释
    """
    # 移除多行注释 /* ... */
    json_str = re.sub(r'/\*.*?\*/', '', json_str, flags=re.DOTALL)
    # 移除单行注释 // ...
    json_str = re.sub(r'//.*', '', json_str)
    return json_str

def get_pages():
    """读取 pages.json 并解析出所有页面的 path"""
    if not os.path.exists(PAGES_JSON_PATH):
        print(f"找不到文件: {PAGES_JSON_PATH}")
        return []
        
    try:
        with open(PAGES_JSON_PATH, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 清理注释后解析 JSON
        clean_content = clean_json_string(content)
        data = json.loads(clean_content)
        
        pages = []
        if 'pages' in data:
            for page in data['pages']:
                pages.append({
                    'path': page.get('path', ''),
                    'title': page.get('style', {}).get('navigationBarTitleText', '未命名')
                })
        return pages
    except Exception as e:
        print(f"解析 pages.json 失败: {e}")
        return []

def take_screenshots():
    """使用 Playwright 进行截图"""
    pages = get_pages()
    if not pages:
        print("没有找到页面配置,退出。")
        return

    print(f"找到 {len(pages)} 个页面,准备开始截图...")
    
    with sync_playwright() as p:
        # 启动浏览器 (这里使用 chromium,模拟移动设备体验更好)
        browser = p.chromium.launch(headless=True)
        
        # 创建上下文,模拟 iPhone 13 尺寸 (方便展示 H5 效果)
        context = browser.new_context(
            viewport={'width': 390, 'height': 844},
            user_agent='Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1',
            device_scale_factor=2, # 高清截图
            is_mobile=True,
            has_touch=True
        )
        
        page = context.new_page()
        
        for idx, item in enumerate(pages):
            path = item['path']
            title = item['title']
            
            # 清理文件名中可能导致错误的特殊字符
            safe_title = re.sub(r'[\\/*?:"<>|]', "", title)
            # 文件名格式: 01_首页_pages_index_index.png
            file_name = f"{idx+1:02d}_{safe_title}_{path.replace('/', '_')}.png"
            file_path = os.path.join(OUTPUT_DIR, file_name)
            
            url = f"{BASE_URL}{path}"
            print(f"正在截图 ({idx+1}/{len(pages)}): {title} -> {url}")
            
            try:
                # 访问页面,等待网络空闲
                page.goto(url, wait_until="networkidle", timeout=15000)
                
                # 等待一小段时间,确保动态渲染完成 (例如轮播图、异步组件)
                page.wait_for_timeout(2000)
                
                # 为了解决长页面的懒加载问题,进行模拟滚动到底部
                page.evaluate("""
                    async () => {
                        await new Promise((resolve) => {
                            let totalHeight = 0;
                            let distance = 100;
                            let timer = setInterval(() => {
                                let scrollHeight = document.body.scrollHeight;
                                window.scrollBy(0, distance);
                                totalHeight += distance;
                                if(totalHeight >= scrollHeight){
                                    clearInterval(timer);
                                    window.scrollTo(0, 0); // 滚回顶部
                                    resolve();
                                }
                            }, 100);
                        });
                    }
                """)
                
                # 滚动完毕后再等一小下,确保图片都加载出来了
                page.wait_for_timeout(1000)
                
                # 执行完整长截图 (full_page=True)
                page.screenshot(path=file_path, full_page=True)
                print(f"保存成功: {file_name}")
                
            except Exception as e:
                print(f"截图失败 {url}: {e}")
                
        browser.close()
        print(f"\n所有截图已完成,保存在目录: {OUTPUT_DIR}")

if __name__ == "__main__":
    take_screenshots()


点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部