page_chart.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 capture_health(page, out_dir: str) -> List[str]:
  76. _goto(page, "/home/health/index")
  77. paths = []
  78. p = _save_shot(page, out_dir, "health_page")
  79. if p:
  80. paths.append(p)
  81. return paths
  82. def capture_algorithm_health(page, out_dir: str) -> List[str]:
  83. _goto(page, "/home/health/index")
  84. paths = []
  85. try:
  86. page.locator("button", has_text="算法健康评估").first.click()
  87. time.sleep(2)
  88. p = _save_shot(page, out_dir, "algorithm_health_dialog", selector=".el-dialog")
  89. if p:
  90. paths.append(p)
  91. except Exception:
  92. pass
  93. if not paths:
  94. p = _save_shot(page, out_dir, "algorithm_health_page")
  95. if p:
  96. paths.append(p)
  97. return paths
  98. def capture_fault(page, out_dir: str) -> List[str]:
  99. _goto(page, "/home/health/malfunction")
  100. paths = []
  101. p = _save_shot(page, out_dir, "fault_page")
  102. if p:
  103. paths.append(p)
  104. return paths
  105. def capture_vibration(page, out_dir: str) -> List[str]:
  106. _goto(page, "/home/health/vibration")
  107. paths = []
  108. p = _save_shot(page, out_dir, "vibration_page")
  109. if p:
  110. paths.append(p)
  111. return paths
  112. def capture_page_charts(wind_code: str, start: str, end: str, out_dir: str) -> Dict[str, List[str]]:
  113. """抓取五个页面的原图;失败返回空列表。"""
  114. from playwright.sync_api import sync_playwright
  115. result: Dict[str, List[str]] = {}
  116. try:
  117. with sync_playwright() as p:
  118. browser = p.chromium.launch(executable_path=CHROME, headless=True, args=["--no-sandbox"])
  119. page = browser.new_page(viewport={"width": 1600, "height": 1000})
  120. page.set_default_timeout(30000)
  121. try:
  122. _login(page)
  123. result["overview"] = capture_overview(page, out_dir, wind_code, start, end)
  124. result["health"] = capture_health(page, out_dir)
  125. result["algorithm_health"] = capture_algorithm_health(page, out_dir)
  126. result["fault"] = capture_fault(page, out_dir)
  127. result["vibration"] = capture_vibration(page, out_dir)
  128. finally:
  129. browser.close()
  130. except Exception as exc:
  131. result["_error"] = str(exc)
  132. return result