page_chart.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """报告页面原图抓取:登录平台、打开五个功能页面,导出页面图表为 PNG。
  2. 抓取结果按 section 保存到输出目录,供 template_builder 嵌入报告。
  3. 抓取失败不阻塞报告生成,对应章节回退到报告自绘图。
  4. """
  5. from __future__ import annotations
  6. import os
  7. import time
  8. from typing import Dict, List
  9. CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
  10. LOGIN_URL = "http://127.0.0.1:8080/login"
  11. BASE = "http://127.0.0.1:8080"
  12. USER = "hd"
  13. PASSWORD = "1234qwer"
  14. def _login(page) -> None:
  15. page.goto(LOGIN_URL, wait_until="networkidle", timeout=45000)
  16. page.fill('input[placeholder="请输入用户名或账号"]', USER)
  17. page.fill('input[placeholder="请输入密码"]', PASSWORD)
  18. page.click('button:has-text("登录")')
  19. page.wait_for_timeout(7000)
  20. def _goto(page, path: str) -> bool:
  21. page.goto(BASE + path, wait_until="domcontentloaded", timeout=60000)
  22. time.sleep(6)
  23. return True
  24. def _save_shot(page, out_dir: str, name: str, selector: str = None) -> str:
  25. os.makedirs(out_dir, exist_ok=True)
  26. path = os.path.join(out_dir, f"{name}.png")
  27. try:
  28. if selector:
  29. el = page.locator(selector).first
  30. el.scroll_into_view_if_needed()
  31. time.sleep(0.6)
  32. el.screenshot(path=path)
  33. else:
  34. page.screenshot(path=path)
  35. return path
  36. except Exception:
  37. return ""
  38. def capture_overview(page, out_dir: str, wind_code: str, start: str, end: str) -> List[str]:
  39. """分析概览:有功功率曲线页面图(Plotly)。"""
  40. batch = f"{wind_code}-ANALYSIS-{start.replace('-', '')}-{end.replace('-', '')}"
  41. page.goto(f"{BASE}/home/performance/overview?batchCode={batch}", wait_until="domcontentloaded", timeout=60000)
  42. time.sleep(7)
  43. try:
  44. page.wait_for_selector(".el-tree-node__content", timeout=30000)
  45. except Exception:
  46. pass
  47. page.evaluate(
  48. "()=>{try{const t=document.querySelector('.el-tree');if(t&&t.__vue__){"
  49. "const s=t.__vue__.store;s._getAllNodes().forEach(n=>n.expanded=true)}}catch(e){}}"
  50. )
  51. time.sleep(1.5)
  52. for i in range(page.locator(".el-tree-node__content").count()):
  53. el = page.locator(".el-tree-node__content").nth(i)
  54. if el.inner_text().strip() == "分析概览":
  55. el.click()
  56. break
  57. time.sleep(4)
  58. try:
  59. page.locator(".el-menu .el-submenu__title").filter(has_text="功率曲线分析").first.click()
  60. time.sleep(1.2)
  61. page.locator(".el-menu .el-menu-item").filter(has_text="有功功率曲线").first.click()
  62. time.sleep(8)
  63. except Exception:
  64. pass
  65. paths = []
  66. for idx in range(page.locator(".js-plotly-plot").count()):
  67. p = _save_shot(page, out_dir, f"overview_powercurve_{idx}", selector=f".js-plotly-plot >> nth={idx}")
  68. if p:
  69. paths.append(p)
  70. if not paths:
  71. p = _save_shot(page, out_dir, "overview_page")
  72. if p:
  73. paths.append(p)
  74. return paths
  75. def _shot_canvas(page, out_dir: str, name: str) -> str:
  76. """抓取页面中第一个可见的 ECharts canvas。"""
  77. try:
  78. for i in range(page.locator("canvas").count()):
  79. el = page.locator("canvas").nth(i)
  80. box = el.bounding_box()
  81. if box and box["width"] > 200 and box["height"] > 100:
  82. el.screenshot(path=os.path.join(out_dir, f"{name}.png"))
  83. return os.path.join(out_dir, f"{name}.png")
  84. except Exception:
  85. pass
  86. return ""
  87. def capture_health(page, out_dir: str) -> List[str]:
  88. # 健康评估页面展示的是评分表格,无 ECharts/Plotly 图,不抓整页截图。
  89. return []
  90. def capture_algorithm_health(page, out_dir: str) -> List[str]:
  91. # 算法健康评估页面展示的是评分表格,无图表,不抓整页截图。
  92. return []
  93. def capture_fault(page, out_dir: str) -> List[str]:
  94. page.goto(
  95. f"{BASE}/home/health/malfunction?windCode=WOF046400029&engineCode=WOG01315&month=2024-11",
  96. wait_until="domcontentloaded", timeout=60000,
  97. )
  98. time.sleep(7)
  99. try:
  100. page.locator(".search-btn", has_text="查询").first.click()
  101. time.sleep(9)
  102. except Exception:
  103. pass
  104. paths = []
  105. p = _shot_canvas(page, out_dir, "fault_chart")
  106. if p:
  107. paths.append(p)
  108. return paths
  109. def capture_vibration(page, out_dir: str) -> List[str]:
  110. _goto(page, "/home/health/vibration")
  111. try:
  112. page.locator(".searchbox .el-button", has_text="查询").first.click()
  113. time.sleep(7)
  114. except Exception:
  115. pass
  116. try:
  117. page.locator(".picture", has_text="频谱图").first.click()
  118. time.sleep(8)
  119. except Exception:
  120. pass
  121. paths = []
  122. p = _shot_canvas(page, out_dir, "vibration_chart")
  123. if p:
  124. paths.append(p)
  125. return paths
  126. def capture_page_charts(wind_code: str, start: str, end: str, out_dir: str) -> Dict[str, List[str]]:
  127. """抓取五个页面的原图;失败返回空列表。"""
  128. from playwright.sync_api import sync_playwright
  129. result: Dict[str, List[str]] = {}
  130. try:
  131. with sync_playwright() as p:
  132. browser = p.chromium.launch(executable_path=CHROME, headless=True, args=["--no-sandbox"])
  133. page = browser.new_page(viewport={"width": 1600, "height": 1000})
  134. page.set_default_timeout(30000)
  135. try:
  136. _login(page)
  137. result["overview"] = capture_overview(page, out_dir, wind_code, start, end)
  138. result["health"] = capture_health(page, out_dir)
  139. result["algorithm_health"] = capture_algorithm_health(page, out_dir)
  140. result["fault"] = capture_fault(page, out_dir)
  141. result["vibration"] = capture_vibration(page, out_dir)
  142. finally:
  143. browser.close()
  144. except Exception as exc:
  145. result["_error"] = str(exc)
  146. return result