web-validation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWeb Validation Skill
网页验证技能
Overview
概述
This skill provides comprehensive methodology for validating web applications, detecting JavaScript errors, monitoring browser console output, capturing screenshots, and testing across mobile and desktop viewports with authentication support.
Key Capabilities:
- Automated JavaScript error detection with categorization
- Browser console log capture (errors, warnings, info)
- Network request monitoring and failure detection
- Performance metrics collection
- Authentication support for protected pages (NEW)
- Screenshot capture for mobile and desktop (NEW)
- React hydration error detection (#185) (NEW)
- Multi-viewport testing (14 device presets) (NEW)
- HTML/CSS validation
- Automated testing with headless browsers
本技能提供了一套全面的Web应用验证方法,可检测JavaScript错误、监控浏览器控制台输出、捕获截图,并支持在移动端和桌面端视口进行带身份验证的测试。
核心功能:
- 带分类功能的自动化JavaScript错误检测
- 浏览器控制台日志捕获(错误、警告、信息)
- 网络请求监控与失败检测
- 性能指标收集
- 受保护页面的身份验证支持(新增)
- 移动端与桌面端截图捕获(新增)
- React Hydration错误检测(#185,新增)
- 多视口测试(14种设备预设,新增)
- HTML/CSS验证
- 基于无头浏览器的自动化测试
When to Apply This Skill
适用场景
Use this skill when:
- Validating web-based dashboards (e.g., dashboard.py)
- Detecting JavaScript syntax errors automatically
- Monitoring console output without manual browser inspection
- Testing web applications before deployment
- Debugging web page issues
- Ensuring cross-browser compatibility
- Validating after code changes to web components
- Testing authenticated/protected pages
- Capturing visual evidence for debugging
- Testing responsive design across devices
- Detecting React hydration mismatches
在以下场景使用本技能:
- 验证基于Web的仪表板(例如dashboard.py)
- 自动检测JavaScript语法错误
- 无需手动检查浏览器即可监控控制台输出
- 部署前测试Web应用
- 调试网页问题
- 确保跨浏览器兼容性
- 修改Web组件代码后进行验证
- 测试需身份验证的受保护页面
- 捕获调试所需的可视化证据
- 跨设备测试响应式设计
- 检测React Hydration不匹配问题
Authentication Support (NEW)
身份验证支持(新增)
Form-Based Authentication
基于表单的身份验证
Validate protected pages by automatically logging in:
python
from lib.web_page_validator import WebPageValidator, AuthConfig
auth = AuthConfig(
login_url="http://localhost:3000/auth/signin",
email="test@example.com",
password="TestPass123!",
email_selector='input[type="email"]',
password_selector='input[type="password"]',
submit_selector='button[type="submit"]',
post_login_wait=2.0
)
with WebPageValidator(auth_config=auth) as validator:
validator.authenticate()
result = validator.validate_url('http://localhost:3000/dashboard')通过自动登录验证受保护页面:
python
from lib.web_page_validator import WebPageValidator, AuthConfig
auth = AuthConfig(
login_url="http://localhost:3000/auth/signin",
email="test@example.com",
password="TestPass123!",
email_selector='input[type="email"]',
password_selector='input[type="password"]',
submit_selector='button[type="submit"]',
post_login_wait=2.0
)
with WebPageValidator(auth_config=auth) as validator:
validator.authenticate()
result = validator.validate_url('http://localhost:3000/dashboard')Environment Variables
环境变量配置
Credentials can be set via environment variables for CI/CD:
bash
export TEST_EMAIL="test@example.com"
export TEST_PASSWORD="TestPass123!"可通过环境变量设置凭据,适用于CI/CD流程:
bash
export TEST_EMAIL="test@example.com"
export TEST_PASSWORD="TestPass123!"Multi-Page Authentication Flow
多页面身份验证流程
python
undefinedpython
undefinedValidate public and protected pages in one session
在一个会话中验证公开页面和受保护页面
results = validator.validate_pages_with_auth(
public_pages=[
("http://localhost:3000/", "Home"),
("http://localhost:3000/auth/signin", "Sign In"),
],
protected_pages=[
("http://localhost:3000/dashboard", "Dashboard"),
("http://localhost:3000/settings", "Settings"),
]
)
undefinedresults = validator.validate_pages_with_auth(
public_pages=[
("http://localhost:3000/", "Home"),
("http://localhost:3000/auth/signin", "Sign In"),
],
protected_pages=[
("http://localhost:3000/dashboard", "Dashboard"),
("http://localhost:3000/settings", "Settings"),
]
)
undefinedScreenshot Capture (NEW)
截图捕获(新增)
Automatic Screenshots
自动截图
Capture screenshots on validation for visual evidence:
python
from lib.web_page_validator import WebPageValidator, ScreenshotConfig, ViewportConfig
screenshot_config = ScreenshotConfig(
enabled=True,
output_directory=".claude/screenshots",
capture_on_error=True,
capture_on_success=False,
full_page=False
)
with WebPageValidator(screenshot_config=screenshot_config) as validator:
result = validator.validate_url('http://localhost:3000')
for ss in result.screenshots:
print(f"Screenshot: {ss.file_path}")在验证时自动捕获截图作为可视化证据:
python
from lib.web_page_validator import WebPageValidator, ScreenshotConfig, ViewportConfig
screenshot_config = ScreenshotConfig(
enabled=True,
output_directory=".claude/screenshots",
capture_on_error=True,
capture_on_success=False,
full_page=False
)
with WebPageValidator(screenshot_config=screenshot_config) as validator:
result = validator.validate_url('http://localhost:3000')
for ss in result.screenshots:
print(f"Screenshot: {ss.file_path}")Multi-Viewport Screenshots
多视口截图
Capture screenshots across multiple devices:
bash
python lib/web_page_validator.py http://localhost:3000 --viewport all --screenshot跨多种设备捕获截图:
bash
python lib/web_page_validator.py http://localhost:3000 --viewport all --screenshotScreenshot Naming Convention
截图命名规则
Files are named:
{page_name}_{viewport}_{timestamp}.pnghome_desktop_20251204_143022.pngdashboard_mobile_20251204_143025.png
文件命名格式:
{page_name}_{viewport}_{timestamp}.pnghome_desktop_20251204_143022.pngdashboard_mobile_20251204_143025.png
Mobile and Responsive Testing (NEW)
移动端与响应式测试(新增)
Available Device Presets
可用设备预设
| Viewport | Width | Height | Type | Device |
|---|---|---|---|---|
| desktop | 1920 | 1080 | Desktop | Full HD |
| desktop_small | 1280 | 720 | Desktop | HD |
| mobile | 375 | 812 | Mobile | iPhone X/12/13 |
| mobile_small | 320 | 568 | Mobile | iPhone SE |
| tablet | 768 | 1024 | Tablet | iPad |
| ipad_pro | 1024 | 1366 | Tablet | iPad Pro 12.9 |
| android_pixel | 393 | 851 | Mobile | Pixel 5 |
| android_samsung | 360 | 800 | Mobile | Galaxy S21 |
| android_tablet | 800 | 1280 | Tablet | Android Tablet |
| 视口 | 宽度 | 高度 | 类型 | 设备 |
|---|---|---|---|---|
| desktop | 1920 | 1080 | 桌面端 | Full HD |
| desktop_small | 1280 | 720 | 桌面端 | HD |
| mobile | 375 | 812 | 移动端 | iPhone X/12/13 |
| mobile_small | 320 | 568 | 移动端 | iPhone SE |
| tablet | 768 | 1024 | 平板端 | iPad |
| ipad_pro | 1024 | 1366 | 平板端 | iPad Pro 12.9 |
| android_pixel | 393 | 851 | 移动端 | Pixel 5 |
| android_samsung | 360 | 800 | 移动端 | Galaxy S21 |
| android_tablet | 800 | 1280 | 平板端 | Android Tablet |
Mobile-First Testing
移动端优先测试
python
from lib.web_page_validator import WebPageValidator, ViewportConfigpython
from lib.web_page_validator import WebPageValidator, ViewportConfigTest on mobile viewport
在移动端视口测试
validator = WebPageValidator(default_viewport=ViewportConfig.mobile())
result = validator.validate_url('http://localhost:3000')
validator = WebPageValidator(default_viewport=ViewportConfig.mobile())
result = validator.validate_url('http://localhost:3000')
Test all viewports
在所有视口测试
results = validator.validate_all_viewports('http://localhost:3000')
undefinedresults = validator.validate_all_viewports('http://localhost:3000')
undefinedCLI Mobile Testing
CLI移动端测试
bash
undefinedbash
undefinedMobile viewport
移动端视口
python lib/web_page_validator.py http://localhost:3000 --viewport mobile
python lib/web_page_validator.py http://localhost:3000 --viewport mobile
Tablet viewport
平板端视口
python lib/web_page_validator.py http://localhost:3000 --viewport tablet
python lib/web_page_validator.py http://localhost:3000 --viewport tablet
All viewports
所有视口
python lib/web_page_validator.py http://localhost:3000 --viewport all
python lib/web_page_validator.py http://localhost:3000 --viewport all
Custom dimensions
自定义尺寸
python lib/web_page_validator.py http://localhost:3000 --viewport-width 414 --viewport-height 896
undefinedpython lib/web_page_validator.py http://localhost:3000 --viewport-width 414 --viewport-height 896
undefinedReact Hydration Error Detection (NEW)
React Hydration错误检测(新增)
What is Hydration Error #185?
什么是Hydration错误#185?
React hydration errors occur when server-rendered HTML doesn't match client-rendered content. This causes:
- Minified React error #185
- "Something went wrong" error boundary
- Content flickering or missing UI elements
React Hydration错误发生在服务端渲染的HTML与客户端渲染的内容不匹配时,会导致:
- 压缩后的React错误#185
- “Something went wrong”错误边界
- 内容闪烁或UI元素缺失
Automatic Detection
自动检测
The validator automatically detects:
- Console messages containing "#185" or "hydration"
- Error boundary UI ("Something went wrong")
- React Error Overlay presence
- Next.js hydration warnings
python
result = validator.validate_url('http://localhost:3000')
if result.has_react_hydration_error:
print("[CRITICAL] React hydration mismatch detected!")
if result.error_boundary_visible:
print("[WARN] Error boundary is visible to users!")验证器会自动检测:
- 包含“#185”或“hydration”的控制台消息
- 错误边界UI(“Something went wrong”)
- React Error Overlay的存在
- Next.js Hydration警告
python
result = validator.validate_url('http://localhost:3000')
if result.has_react_hydration_error:
print("[CRITICAL] React hydration mismatch detected!")
if result.error_boundary_visible:
print("[WARN] Error boundary is visible to users!")Error Categories
错误分类
Errors are automatically categorized:
- - React #185 and hydration mismatches
REACT_HYDRATION - - SyntaxError
JAVASCRIPT_SYNTAX - - TypeError, ReferenceError
JAVASCRIPT_RUNTIME - - Failed HTTP requests
NETWORK_FAILURE - - Unhandled exceptions
UNCAUGHT_EXCEPTION - - Generic console.error
CONSOLE_ERROR
错误会被自动分类:
- - React #185及Hydration不匹配问题
REACT_HYDRATION - - 语法错误
JAVASCRIPT_SYNTAX - - 类型错误、引用错误
JAVASCRIPT_RUNTIME - - HTTP请求失败
NETWORK_FAILURE - - 未处理的异常
UNCAUGHT_EXCEPTION - - 通用控制台错误
CONSOLE_ERROR
Validation Methodology
验证方法
1. Automated Browser Testing
1. 自动化浏览器测试
Approach: Use headless browser automation to capture real browser behavior
Tools:
- Selenium WebDriver: Industry standard for browser automation
- Playwright: Modern alternative with better API
- Chrome DevTools Protocol: Direct browser control
Implementation:
python
from lib.web_page_validator import WebPageValidator
with WebPageValidator(headless=True) as validator:
result = validator.validate_url('http://127.0.0.1:5000')
if not result.success:
print(f"Found {len(result.console_errors)} errors")
for error in result.console_errors:
print(f" - {error.message}")方法:使用无头浏览器自动化捕获真实浏览器行为
工具:
- Selenium WebDriver: 浏览器自动化行业标准
- Playwright: 更现代的替代方案,API更友好
- Chrome DevTools Protocol: 直接控制浏览器
实现示例:
python
from lib.web_page_validator import WebPageValidator
with WebPageValidator(headless=True) as validator:
result = validator.validate_url('http://127.0.0.1:5000')
if not result.success:
print(f"Found {len(result.console_errors)} errors")
for error in result.console_errors:
print(f" - {error.message}")2. Console Log Monitoring
2. 控制台日志监控
Types of Console Logs:
- Errors: Critical issues that break functionality
- Warnings: Potential problems that should be addressed
- Info: Informational messages for debugging
- Logs: General debug output
Capture Strategy:
javascript
// Enable console capture in browser
chrome_options.set_capability('goog:loggingPrefs', {'browser': 'ALL'})
// Retrieve logs after page load
logs = driver.get_log('browser')
for log in logs:
if log['level'] == 'SEVERE':
# Critical error detected
handle_error(log['message'])控制台日志类型:
- 错误: 破坏功能的严重问题
- 警告: 需要处理的潜在问题
- 信息: 用于调试的参考消息
- 日志: 通用调试输出
捕获策略:
javascript
// 启用浏览器控制台捕获
chrome_options.set_capability('goog:loggingPrefs', {'browser': 'ALL'})
// 页面加载后获取日志
logs = driver.get_log('browser')
for log in logs:
if log['level'] == 'SEVERE':
# 检测到严重错误
handle_error(log['message'])3. JavaScript Error Detection
3. JavaScript错误检测
Common JavaScript Error Patterns:
- SyntaxError: Invalid JavaScript syntax
- ReferenceError: Undefined variables or functions
- TypeError: Invalid type operations
- Uncaught exceptions: Unhandled runtime errors
Detection Methods:
- Browser console logs (level: SEVERE)
- window.onerror event handler
- Promise rejection tracking
- Resource loading failures
Example Detection:
python
undefined常见JavaScript错误类型:
- SyntaxError: 无效JavaScript语法
- ReferenceError: 未定义的变量或函数
- TypeError: 无效类型操作
- Uncaught exceptions: 未处理的运行时错误
检测方法:
- 浏览器控制台日志(级别:SEVERE)
- window.onerror事件处理器
- Promise拒绝跟踪
- 资源加载失败检测
检测示例:
python
undefinedCheck for SyntaxError in console logs
检查控制台日志中的SyntaxError
for log in console_logs:
if 'SyntaxError' in log.message:
# Extract line number and source
# Parse error message
# Generate fix suggestions
undefinedfor log in console_logs:
if 'SyntaxError' in log.message:
# 提取行号和来源
# 解析错误消息
# 生成修复建议
undefined4. Network Request Monitoring
4. 网络请求监控
What to Monitor:
- Failed HTTP requests (404, 500, etc.)
- Timeout errors
- CORS issues
- Missing resources (CSS, JS, images)
- Slow-loading resources
Performance Metrics:
javascript
// Collect Resource Timing data
const resources = performance.getEntriesByType('resource');
resources.forEach(r => {
if (r.transferSize === 0 && r.duration > 0) {
// Resource failed to load
console.error(`Failed to load: ${r.name}`);
}
});监控内容:
- 失败的HTTP请求(404、500等)
- 超时错误
- CORS问题
- 缺失的资源(CSS、JS、图片)
- 加载缓慢的资源
性能指标:
javascript
// 收集资源计时数据
const resources = performance.getEntriesByType('resource');
resources.forEach(r => {
if (r.transferSize === 0 && r.duration > 0) {
// 资源加载失败
console.error(`Failed to load: ${r.name}`);
}
});5. Performance Validation
5. 性能验证
Key Metrics:
- Load Time: Total page load duration
- DOM Ready: Time until DOM is interactive
- First Contentful Paint: Time until first content renders
- Resource Count: Number of loaded resources
- Page Size: Total transfer size
Thresholds:
- Load time < 3 seconds (good)
- Load time 3-5 seconds (acceptable)
- Load time > 5 seconds (needs optimization)
关键指标:
- 加载时间: 页面总加载时长
- DOM Ready: DOM可交互的时间
- 首次内容绘制: 首次内容渲染的时间
- 资源数量: 已加载资源的数量
- 页面大小: 总传输大小
阈值:
- 加载时间 < 3秒(良好)
- 加载时间 3-5秒(可接受)
- 加载时间 > 5秒(需要优化)
Validation Workflow
验证流程
Pre-Deployment Validation
部署前验证
Step 1: Start Web Server
bash
python lib/dashboard.py --no-browser --port 5000 &Step 2: Wait for Server Ready
python
import time
import urllib.request
def wait_for_server(url, timeout=30):
start = time.time()
while time.time() - start < timeout:
try:
urllib.request.urlopen(url, timeout=1)
return True
except:
time.sleep(0.5)
return False
wait_for_server('http://127.0.0.1:5000')Step 3: Run Validation
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --verboseStep 4: Analyze Results
python
if result.success:
print("[OK] No errors detected")
else:
print(f"[ERROR] Found {len(result.console_errors)} errors")
# Auto-fix or report to user步骤1:启动Web服务器
bash
python lib/dashboard.py --no-browser --port 5000 &步骤2:等待服务器就绪
python
import time
import urllib.request
def wait_for_server(url, timeout=30):
start = time.time()
while time.time() - start < timeout:
try:
urllib.request.urlopen(url, timeout=1)
return True
except:
time.sleep(0.5)
return False
wait_for_server('http://127.0.0.1:5000')步骤3:运行验证
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --verbose步骤4:分析结果
python
if result.success:
print("[OK] No errors detected")
else:
print(f"[ERROR] Found {len(result.console_errors)} errors")
# 自动修复或向用户报告Continuous Validation
持续验证
Integration Points:
- On dashboard startup: Automatically validate after server starts
- After code changes: Run validation in git pre-commit hook
- Scheduled monitoring: Periodic validation of running dashboards
- CI/CD pipeline: Automated testing before deployment
集成点:
- 仪表板启动时: 服务器启动后自动运行验证
- 代码变更后: 在git预提交钩子中运行验证
- 定时监控: 定期验证运行中的仪表板
- CI/CD流水线: 部署前自动测试
Error Analysis and Auto-Fix
错误分析与自动修复
Common Issues and Fixes:
1. Literal Newlines in JavaScript Strings
python
undefined常见问题与修复方案:
1. JavaScript字符串中的字面量换行
python
undefinedProblem: csvContent = 'Header\n' # Python processes \n
问题: csvContent = 'Header\n' # Python会处理\n
Fix: csvContent = r'Header\n' # Raw string preserves \n
修复: csvContent = r'Header\n' # 原始字符串保留\n
**2. Template Literal Interpolation**
```javascript
// Problem: `Value: $0` # Tries to interpolate $0
// Fix: `Value: \$0` # Escape the dollar sign3. Missing Resource Files
python
undefined
**2. 模板字面量插值**
```javascript
// 问题: `Value: $0` # 尝试插值$0
// 修复: `Value: \$0` # 转义美元符号3. 缺失的资源文件
python
undefinedProblem: 404 errors for CSS/JS files
问题: CSS/JS文件出现404错误
Fix: Check file paths and ensure resources exist
修复: 检查文件路径并确保资源存在
**4. CORS Issues**
```python
**4. CORS问题**
```pythonProblem: Cross-origin request blocked
问题: 跨域请求被阻止
Fix: Add CORS headers to Flask app
修复: 为Flask应用添加CORS头
from flask_cors import CORS
CORS(app)
undefinedfrom flask_cors import CORS
CORS(app)
undefinedBest Practices
最佳实践
1. Validation Coverage
1. 验证覆盖范围
Essential Checks:
- Page loads successfully (HTTP 200)
- No JavaScript syntax errors
- No console errors
- All resources load (CSS, JS, images)
- Page title is correct
- Load time is acceptable (< 5s)
Recommended Checks:
- No console warnings
- Performance metrics within thresholds
- Mobile responsiveness
- Accessibility compliance
- Cross-browser compatibility
必备检查项:
- 页面成功加载(HTTP 200)
- 无JavaScript语法错误
- 无控制台错误
- 所有资源加载完成(CSS、JS、图片)
- 页面标题正确
- 加载时间可接受(<5秒)
推荐检查项:
- 无控制台警告
- 性能指标在阈值内
- 移动端响应正常
- 符合无障碍标准
- 跨浏览器兼容性
2. Error Reporting
2. 错误报告
Report Structure:
=== WEB PAGE VALIDATION REPORT ===
URL: http://127.0.0.1:5000
Status: FAILED
Load Time: 2.34s
CONSOLE ERRORS (3):
1. [SEVERE] Uncaught SyntaxError: Invalid or unexpected token
Source: http://127.0.0.1:5000/:1827
Time: 2025-11-06T09:00:00
JAVASCRIPT ERRORS (1):
1. Uncaught SyntaxError: Invalid or unexpected token at line 1827
RECOMMENDATIONS:
1. Fix JavaScript syntax errors in source files
2. Use Python raw strings (r'...') for JavaScript escape sequences
3. Validate JavaScript code before deployment报告结构:
=== 网页验证报告 ===
URL: http://127.0.0.1:5000
状态: 失败
加载时间: 2.34s
控制台错误(3):
1. [严重] Uncaught SyntaxError: Invalid or unexpected token
来源: http://127.0.0.1:5000/:1827
时间: 2025-11-06T09:00:00
JavaScript错误(1):
1. 第1827行出现Uncaught SyntaxError: Invalid or unexpected token
建议:
1. 修复源文件中的JavaScript语法错误
2. 对JavaScript转义序列使用Python原始字符串(r'...')
3. 部署前验证JavaScript代码3. Automated Remediation
3. 自动修复
When Auto-Fix is Safe:
- String escaping issues (add raw strings)
- Missing CORS headers (add to Flask config)
- Outdated dependencies (update requirements.txt)
- Simple syntax errors (apply known patterns)
When Manual Review Required:
- Logic errors in JavaScript
- Complex refactoring needed
- Security-related issues
- Breaking changes to API
适合自动修复的场景:
- 字符串转义问题(添加原始字符串)
- 缺失的CORS头(添加到Flask配置)
- 过时的依赖(更新requirements.txt)
- 简单的语法错误(应用已知修复模式)
需要人工审核的场景:
- JavaScript逻辑错误
- 需要复杂重构的问题
- 安全相关问题
- 会破坏API的变更
4. Integration with Quality Control
4. 与质量控制集成
Quality Score Impact:
- 0 errors: Full credit (20/20 points)
- 1-2 warnings: Minor deduction (18/20 points)
- 1-2 errors: Moderate deduction (12/20 points)
- 3+ errors: Significant deduction (5/20 points)
- Critical errors: Automatic failure (0/20 points)
对质量分数的影响:
- 0错误: 满分(20/20分)
- 1-2个警告: 轻微扣分(18/20分)
- 1-2个错误: 中等扣分(12/20分)
- 3+个错误: 严重扣分(5/20分)
- 严重错误: 直接不合格(0/20分)
Tool Usage
工具使用
Command-Line Usage
命令行使用
Basic Validation:
bash
python lib/web_page_validator.py http://127.0.0.1:5000Verbose Output:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --verboseSave Report to File:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --output report.txtJSON Output:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --json > result.jsonShow Browser (Debugging):
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --no-headless基础验证:
bash
python lib/web_page_validator.py http://127.0.0.1:5000详细输出:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --verbose保存报告到文件:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --output report.txtJSON输出:
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --json > result.json显示浏览器(调试用):
bash
python lib/web_page_validator.py http://127.0.0.1:5000 --no-headlessProgrammatic Usage
编程式使用
Python Integration:
python
from lib.web_page_validator import WebPageValidator, format_validation_reportPython集成:
python
from lib.web_page_validator import WebPageValidator, format_validation_reportValidate URL
验证URL
with WebPageValidator(headless=True, timeout=30) as validator:
result = validator.validate_url('http://127.0.0.1:5000', wait_for_load=3)
with WebPageValidator(headless=True, timeout=30) as validator:
result = validator.validate_url('http://127.0.0.1:5000', wait_for_load=3)
Check success
检查验证结果
if result.success:
print("[OK] Page validated successfully")
else:
print(f"[ERROR] Validation failed: {result.error_summary}")
# Get detailed report
report = format_validation_report(result, verbose=True)
print(report)
# Access specific errors
for error in result.console_errors:
print(f"Error: {error.message}")undefinedif result.success:
print("[OK] 页面验证通过")
else:
print(f"[ERROR] 验证失败: {result.error_summary}")
# 获取详细报告
report = format_validation_report(result, verbose=True)
print(report)
# 查看具体错误
for error in result.console_errors:
print(f"错误: {error.message}")undefinedSlash Command Usage
斜杠命令使用
bash
undefinedbash
undefinedValidate dashboard at default URL
验证默认URL的仪表板
/validate:web http://127.0.0.1:5000
/validate:web http://127.0.0.1:5000
Validate with auto-fix enabled
启用自动修复的验证
/validate:web http://127.0.0.1:5000 --auto-fix
/validate:web http://127.0.0.1:5000 --auto-fix
Validate and save report
验证并保存报告
/validate:web http://127.0.0.1:5000 --report
undefined/validate:web http://127.0.0.1:5000 --report
undefinedInstallation Requirements
安装要求
Required Dependencies
必需依赖
Selenium (Recommended):
bash
pip install seleniumChromeDriver (for Selenium):
- Download from: https://chromedriver.chromium.org/
- Or use:
pip install webdriver-manager
Playwright (Alternative):
bash
pip install playwright
playwright install chromiumSelenium(推荐):
bash
pip install seleniumChromeDriver(用于Selenium):
- 下载地址: https://chromedriver.chromium.org/
- 或使用:
pip install webdriver-manager
Playwright(替代方案):
bash
pip install playwright
playwright install chromiumMinimal Installation
最小化安装
If browser automation is not available, the tool falls back to basic HTTP validation:
- No additional dependencies required
- Limited error detection
- No console log capture
- Basic connectivity and HTTP status checking only
如果无法使用浏览器自动化,工具会回退到基础HTTP验证:
- 无需额外依赖
- 错误检测能力有限
- 无法捕获控制台日志
- 仅支持基础连通性和HTTP状态检查
Integration Examples
集成示例
Dashboard Startup Validation
仪表板启动验证
Modify dashboard command to auto-validate:
python
undefined修改仪表板命令以自动验证:
python
undefinedIn commands/monitor/dashboard.md
在commands/monitor/dashboard.md中
After starting server, run validation
启动服务器后运行验证
subprocess.Popen(['python', 'lib/dashboard.py', '--no-browser', '--port', '5000'])
time.sleep(3) # Wait for server to start
subprocess.Popen(['python', 'lib/dashboard.py', '--no-browser', '--port', '5000'])
time.sleep(3) # 等待服务器启动
Validate
运行验证
result = subprocess.run(
['python', 'lib/web_page_validator.py', 'http://127.0.0.1:5000'],
capture_output=True
)
if result.returncode != 0:
print("[WARN] Dashboard validation failed, see report for details")
undefinedresult = subprocess.run(
['python', 'lib/web_page_validator.py', 'http://127.0.0.1:5000'],
capture_output=True
)
if result.returncode != 0:
print("[WARN] 仪表板验证失败,详情请查看报告")
undefinedGit Pre-Commit Hook
Git预提交钩子
Validate before committing dashboard changes:
bash
#!/bin/bash提交仪表板变更前进行验证:
bash
#!/bin/bash.git/hooks/pre-commit
.git/hooks/pre-commit
Check if dashboard.py was modified
检查dashboard.py是否被修改
if git diff --cached --name-only | grep -q "dashboard.py"; then
echo "Running dashboard validation..."
# Start server
python lib/dashboard.py --no-browser --port 5555 &
PID=$!
sleep 3
# Validate
python lib/web_page_validator.py http://127.0.0.1:5555
RESULT=$?
# Cleanup
kill $PID
if [ $RESULT -ne 0 ]; then
echo "ERROR: Dashboard validation failed"
exit 1
fifi
undefinedif git diff --cached --name-only | grep -q "dashboard.py"; then
echo "正在运行仪表板验证..."
# 启动服务器
python lib/dashboard.py --no-browser --port 5555 &
PID=$!
sleep 3
# 运行验证
python lib/web_page_validator.py http://127.0.0.1:5555
RESULT=$?
# 清理进程
kill $PID
if [ $RESULT -ne 0 ]; then
echo "错误: 仪表板验证失败"
exit 1
fifi
undefinedContinuous Monitoring
持续监控
Periodic validation of running dashboard:
python
import schedule
import time
from lib.web_page_validator import WebPageValidator
def validate_dashboard():
with WebPageValidator() as validator:
result = validator.validate_url('http://127.0.0.1:5000')
if not result.success:
# Alert or log errors
print(f"[ALERT] Dashboard errors detected: {result.error_summary}")
# Send notification, log to file, etc.定期验证运行中的仪表板:
python
import schedule
import time
from lib.web_page_validator import WebPageValidator
def validate_dashboard():
with WebPageValidator() as validator:
result = validator.validate_url('http://127.0.0.1:5000')
if not result.success:
# 发出警报或记录错误
print(f"[警报] 检测到仪表板错误: {result.error_summary}")
# 发送通知、写入日志等Run validation every 5 minutes
每5分钟运行一次验证
schedule.every(5).minutes.do(validate_dashboard)
while True:
schedule.run_pending()
time.sleep(1)
undefinedschedule.every(5).minutes.do(validate_dashboard)
while True:
schedule.run_pending()
time.sleep(1)
undefinedTroubleshooting
故障排除
Common Issues
常见问题
1. Selenium WebDriver not found
Solution: Install ChromeDriver
- Download from: https://chromedriver.chromium.org/
- Or: pip install webdriver-manager
- Add to PATH2. Chrome not installed
Solution: Install Google Chrome browser
- Download from: https://www.google.com/chrome/
- Or use Playwright as alternative3. Timeout errors
Solution: Increase timeout
python lib/web_page_validator.py URL --timeout 604. No errors detected but page broken
Solution: Increase wait time after page load
python lib/web_page_validator.py URL --wait 105. Permission denied on Windows
Solution: Run as administrator or disable antivirus temporarily1. Selenium WebDriver未找到
解决方案: 安装ChromeDriver
- 下载地址: https://chromedriver.chromium.org/
- 或使用: pip install webdriver-manager
- 添加到系统PATH2. Chrome未安装
解决方案: 安装Google Chrome浏览器
- 下载地址: https://www.google.com/chrome/
- 或使用Playwright作为替代方案3. 超时错误
解决方案: 增加超时时间
python lib/web_page_validator.py URL --timeout 604. 未检测到错误但页面显示异常
解决方案: 增加页面加载后的等待时间
python lib/web_page_validator.py URL --wait 105. Windows系统下权限被拒绝
解决方案: 以管理员身份运行或临时禁用杀毒软件Advanced Features
高级功能
Custom Validation Rules
自定义验证规则
Add custom checks:
python
class CustomWebPageValidator(WebPageValidator):
def validate_custom_rules(self, page):
issues = []
# Check for specific elements
if not page.find_element(By.ID, 'dashboard-content'):
issues.append("Missing dashboard-content element")
# Check for required JavaScript globals
has_required_js = page.execute_script("""
return typeof Chart !== 'undefined' &&
typeof dashboardData !== 'undefined';
""")
if not has_required_js:
issues.append("Missing required JavaScript libraries")
return issues添加自定义检查:
python
class CustomWebPageValidator(WebPageValidator):
def validate_custom_rules(self, page):
issues = []
# 检查特定元素
if not page.find_element(By.ID, 'dashboard-content'):
issues.append("缺失dashboard-content元素")
# 检查必需的JavaScript全局变量
has_required_js = page.execute_script("""
return typeof Chart !== 'undefined' &&
typeof dashboardData !== 'undefined';
""")
if not has_required_js:
issues.append("缺失必需的JavaScript库")
return issuesPerformance Budgets
性能预算
Enforce performance thresholds:
python
def validate_performance(result):
budget = {
'loadTime': 3000, # 3 seconds
'domReady': 1000, # 1 second
'resourceCount': 50
}
violations = []
if result.load_time > budget['loadTime'] / 1000:
violations.append(f"Load time exceeds budget: {result.load_time:.2f}s > 3s")
return violations强制执行性能阈值:
python
def validate_performance(result):
budget = {
'loadTime': 3000, # 3秒
'domReady': 1000, # 1秒
'resourceCount': 50
}
violations = []
if result.load_time > budget['loadTime'] / 1000:
violations.append(f"加载时间超出预算: {result.load_time:.2f}s > 3s")
return violationsAccessibility Validation
无障碍验证
Check for accessibility issues:
python
undefined检查无障碍问题:
python
undefinedInstall axe-core for accessibility testing
安装axe-core进行无障碍测试
page.execute_script("""
// Inject axe-core library
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.7.2/axe.min.js';
document.head.appendChild(script);
""")
page.execute_script("""
// 注入axe-core库
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.7.2/axe.min.js';
document.head.appendChild(script);
""")
Run accessibility scan
运行无障碍扫描
results = page.execute_script("return axe.run();")
violations = results.get('violations', [])
undefinedresults = page.execute_script("return axe.run();")
violations = results.get('violations', [])
undefinedSuccess Metrics
成功指标
Validation Quality Indicators:
- 100% error-free: All pages load without console errors
- < 1 second validation time: Fast feedback loop
- Zero false positives: Accurate error detection
- Automated remediation: 80%+ of issues fixed automatically
- Continuous monitoring: 24/7 health checking
验证质量指标:
- 100%无错误: 所有页面加载无控制台错误
- <1秒验证时间: 快速反馈循环
- 零误报: 错误检测准确
- 自动修复率80%+: 大部分问题可自动修复
- 24/7持续监控: 全天候健康检查
Summary
总结
The web validation skill provides:
- Automated error detection without manual browser inspection
- Real-time console monitoring for JavaScript issues
- Comprehensive validation of web applications
- Performance measurement and optimization guidance
- Integration-ready for CI/CD pipelines and quality control
Use this skill whenever working with web-based components to ensure quality and catch errors early in the development cycle.
网页验证技能提供:
- 自动化错误检测: 无需手动检查浏览器
- 实时控制台监控: 及时发现JavaScript问题
- 全面的应用验证: 覆盖多维度测试需求
- 性能测量与优化指导: 提升页面加载速度
- 易于集成: 支持CI/CD流水线与质量控制流程
在处理Web组件时使用本技能,可确保产品质量并在开发周期早期发现错误。