Loading...
Loading...
Comprehensive web page validation with authentication, screenshot capture, mobile testing, and enhanced error detection
npx skill4agent add bejranonda/llm-autonomous-agent-plugin-for-claude web-validationfrom 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')export TEST_EMAIL="test@example.com"
export TEST_PASSWORD="TestPass123!"# Validate 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"),
]
)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 lib/web_page_validator.py http://localhost:3000 --viewport all --screenshot{page_name}_{viewport}_{timestamp}.pnghome_desktop_20251204_143022.pngdashboard_mobile_20251204_143025.png| 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 |
from lib.web_page_validator import WebPageValidator, ViewportConfig
# Test on mobile viewport
validator = WebPageValidator(default_viewport=ViewportConfig.mobile())
result = validator.validate_url('http://localhost:3000')
# Test all viewports
results = validator.validate_all_viewports('http://localhost:3000')# Mobile viewport
python lib/web_page_validator.py http://localhost:3000 --viewport mobile
# Tablet viewport
python lib/web_page_validator.py http://localhost:3000 --viewport tablet
# All viewports
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 896result = 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!")REACT_HYDRATIONJAVASCRIPT_SYNTAXJAVASCRIPT_RUNTIMENETWORK_FAILUREUNCAUGHT_EXCEPTIONCONSOLE_ERRORfrom 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}")// 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'])# Check for SyntaxError in console logs
for log in console_logs:
if 'SyntaxError' in log.message:
# Extract line number and source
# Parse error message
# Generate fix suggestions// 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}`);
}
});python lib/dashboard.py --no-browser --port 5000 &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')python lib/web_page_validator.py http://127.0.0.1:5000 --verboseif result.success:
print("[OK] No errors detected")
else:
print(f"[ERROR] Found {len(result.console_errors)} errors")
# Auto-fix or report to user# Problem: csvContent = 'Header\n' # Python processes \n
# Fix: csvContent = r'Header\n' # Raw string preserves \n// Problem: `Value: $0` # Tries to interpolate $0
// Fix: `Value: \$0` # Escape the dollar sign# Problem: 404 errors for CSS/JS files
# Fix: Check file paths and ensure resources exist# Problem: Cross-origin request blocked
# Fix: Add CORS headers to Flask app
from flask_cors import CORS
CORS(app)=== 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 deploymentpython lib/web_page_validator.py http://127.0.0.1:5000python lib/web_page_validator.py http://127.0.0.1:5000 --verbosepython lib/web_page_validator.py http://127.0.0.1:5000 --output report.txtpython lib/web_page_validator.py http://127.0.0.1:5000 --json > result.jsonpython lib/web_page_validator.py http://127.0.0.1:5000 --no-headlessfrom lib.web_page_validator import WebPageValidator, format_validation_report
# Validate URL
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}")# Validate dashboard at default URL
/validate:web http://127.0.0.1:5000
# Validate with auto-fix enabled
/validate:web http://127.0.0.1:5000 --auto-fix
# Validate and save report
/validate:web http://127.0.0.1:5000 --reportpip install seleniumpip install webdriver-managerpip install playwright
playwright install chromium# In 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
# 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")#!/bin/bash
# .git/hooks/pre-commit
# Check if dashboard.py was modified
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
fi
fiimport 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.
# Run validation every 5 minutes
schedule.every(5).minutes.do(validate_dashboard)
while True:
schedule.run_pending()
time.sleep(1)Solution: Install ChromeDriver
- Download from: https://chromedriver.chromium.org/
- Or: pip install webdriver-manager
- Add to PATHSolution: Install Google Chrome browser
- Download from: https://www.google.com/chrome/
- Or use Playwright as alternativeSolution: Increase timeout
python lib/web_page_validator.py URL --timeout 60Solution: Increase wait time after page load
python lib/web_page_validator.py URL --wait 10Solution: Run as administrator or disable antivirus temporarilyclass 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 issuesdef 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# Install axe-core for accessibility testing
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);
""")
# Run accessibility scan
results = page.execute_script("return axe.run();")
violations = results.get('violations', [])