"""报告页面原图抓取:登录平台、打开五个功能页面,导出页面图表为 PNG。 抓取结果按 section 保存到输出目录,供 template_builder 嵌入报告。 抓取失败不阻塞报告生成,对应章节回退到报告自绘图。 """ from __future__ import annotations import os import time from typing import Dict, List CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe" LOGIN_URL = "http://127.0.0.1:8080/login" BASE = "http://127.0.0.1:8080" USER = "hd" PASSWORD = "1234qwer" def _login(page) -> None: page.goto(LOGIN_URL, wait_until="networkidle", timeout=45000) page.fill('input[placeholder="请输入用户名或账号"]', USER) page.fill('input[placeholder="请输入密码"]', PASSWORD) page.click('button:has-text("登录")') page.wait_for_timeout(7000) def _goto(page, path: str) -> bool: page.goto(BASE + path, wait_until="domcontentloaded", timeout=60000) time.sleep(6) return True def _save_shot(page, out_dir: str, name: str, selector: str = None) -> str: os.makedirs(out_dir, exist_ok=True) path = os.path.join(out_dir, f"{name}.png") try: if selector: el = page.locator(selector).first el.scroll_into_view_if_needed() time.sleep(0.6) el.screenshot(path=path) else: page.screenshot(path=path) return path except Exception: return "" def capture_overview(page, out_dir: str, wind_code: str, start: str, end: str) -> List[str]: """分析概览:有功功率曲线页面图(Plotly)。""" batch = f"{wind_code}-ANALYSIS-{start.replace('-', '')}-{end.replace('-', '')}" page.goto(f"{BASE}/home/performance/overview?batchCode={batch}", wait_until="domcontentloaded", timeout=60000) time.sleep(7) try: page.wait_for_selector(".el-tree-node__content", timeout=30000) except Exception: pass page.evaluate( "()=>{try{const t=document.querySelector('.el-tree');if(t&&t.__vue__){" "const s=t.__vue__.store;s._getAllNodes().forEach(n=>n.expanded=true)}}catch(e){}}" ) time.sleep(1.5) for i in range(page.locator(".el-tree-node__content").count()): el = page.locator(".el-tree-node__content").nth(i) if el.inner_text().strip() == "分析概览": el.click() break time.sleep(4) try: page.locator(".el-menu .el-submenu__title").filter(has_text="功率曲线分析").first.click() time.sleep(1.2) page.locator(".el-menu .el-menu-item").filter(has_text="有功功率曲线").first.click() time.sleep(8) except Exception: pass paths = [] for idx in range(page.locator(".js-plotly-plot").count()): p = _save_shot(page, out_dir, f"overview_powercurve_{idx}", selector=f".js-plotly-plot >> nth={idx}") if p: paths.append(p) if not paths: p = _save_shot(page, out_dir, "overview_page") if p: paths.append(p) return paths def _shot_canvas(page, out_dir: str, name: str) -> str: """抓取页面中第一个可见的 ECharts canvas。""" try: for i in range(page.locator("canvas").count()): el = page.locator("canvas").nth(i) box = el.bounding_box() if box and box["width"] > 200 and box["height"] > 100: el.screenshot(path=os.path.join(out_dir, f"{name}.png")) return os.path.join(out_dir, f"{name}.png") except Exception: pass return "" def capture_health(page, out_dir: str) -> List[str]: # 健康评估页面展示的是评分表格,无 ECharts/Plotly 图,不抓整页截图。 return [] def capture_algorithm_health(page, out_dir: str) -> List[str]: # 算法健康评估页面展示的是评分表格,无图表,不抓整页截图。 return [] def capture_fault(page, out_dir: str) -> List[str]: page.goto( f"{BASE}/home/health/malfunction?windCode=WOF046400029&engineCode=WOG01315&month=2024-11", wait_until="domcontentloaded", timeout=60000, ) time.sleep(7) try: page.locator(".search-btn", has_text="查询").first.click() time.sleep(9) except Exception: pass paths = [] p = _shot_canvas(page, out_dir, "fault_chart") if p: paths.append(p) return paths def capture_vibration(page, out_dir: str) -> List[str]: _goto(page, "/home/health/vibration") try: page.locator(".searchbox .el-button", has_text="查询").first.click() time.sleep(7) except Exception: pass try: page.locator(".picture", has_text="频谱图").first.click() time.sleep(8) except Exception: pass paths = [] p = _shot_canvas(page, out_dir, "vibration_chart") if p: paths.append(p) return paths def capture_page_charts(wind_code: str, start: str, end: str, out_dir: str) -> Dict[str, List[str]]: """抓取五个页面的原图;失败返回空列表。""" from playwright.sync_api import sync_playwright result: Dict[str, List[str]] = {} try: with sync_playwright() as p: browser = p.chromium.launch(executable_path=CHROME, headless=True, args=["--no-sandbox"]) page = browser.new_page(viewport={"width": 1600, "height": 1000}) page.set_default_timeout(30000) try: _login(page) result["overview"] = capture_overview(page, out_dir, wind_code, start, end) result["health"] = capture_health(page, out_dir) result["algorithm_health"] = capture_algorithm_health(page, out_dir) result["fault"] = capture_fault(page, out_dir) result["vibration"] = capture_vibration(page, out_dir) finally: browser.close() except Exception as exc: result["_error"] = str(exc) return result