render-local-html.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // scripts/render-local-html.js — playwright 渲染本地 HTML 文件,提取 DOM 文本
  2. const { chromium } = require('playwright');
  3. const fs = require('fs');
  4. const os = require('os');
  5. const path = require('path');
  6. (async () => {
  7. const filePath = process.argv[2];
  8. const outPath = process.argv[3] || path.join(os.tmpdir(), path.basename(filePath).replace(/\.html$/, '-dom.txt'));
  9. const url = 'file:///' + filePath.replace(/\\/g, '/');
  10. const browser = await chromium.launch({ headless: true });
  11. const page = await browser.newPage();
  12. // 等动态内容(阿里云 SPA 的 React 渲染可能稍慢)
  13. await page.goto(url, { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});
  14. for (let i = 0; i < 6; i++) {
  15. await page.waitForTimeout(2000);
  16. const tables = await page.locator('table').count();
  17. console.log(` attempt ${i + 1}: tables=${tables}`);
  18. if (tables >= 2) break;
  19. }
  20. const text = await page.evaluate(() => {
  21. document.querySelectorAll('script,style,noscript').forEach(e => e.remove());
  22. return document.body.innerText;
  23. });
  24. fs.writeFileSync(outPath, text, 'utf8');
  25. console.log(`dom text: ${text.length} bytes → ${outPath}`);
  26. console.log(`first 300 chars:`);
  27. console.log(text.slice(0, 300));
  28. await browser.close();
  29. })().catch(e => { console.error(e); process.exit(1); });