Spaces:
Running
Running
File size: 4,573 Bytes
ace9c2b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
"""
Network monitoring and performance analysis features
"""
import json
import time
import logging
from browser.driver import get_driver, cleanup_driver
logger = logging.getLogger(__name__)
def monitor_network_requests(url: str, duration: int = 5, use_persistent: bool = False) -> str:
"""Monitor network requests made by a page"""
driver = None
try:
driver = get_driver(None, use_persistent) # Don't navigate yet
# Inject JavaScript to monitor network
monitor_script = """
window.networkRequests = [];
const originalFetch = window.fetch;
const originalXHR = window.XMLHttpRequest.prototype.open;
// Monitor fetch requests
window.fetch = function(...args) {
const request = {
method: args[1]?.method || 'GET',
url: args[0],
timestamp: new Date().toISOString(),
type: 'fetch'
};
window.networkRequests.push(request);
return originalFetch.apply(this, args);
};
// Monitor XHR requests
window.XMLHttpRequest.prototype.open = function(method, url) {
const request = {
method: method,
url: url,
timestamp: new Date().toISOString(),
type: 'xhr'
};
window.networkRequests.push(request);
return originalXHR.apply(this, arguments);
};
"""
# Navigate to page and inject monitoring
driver.get(url)
driver.execute_script(monitor_script)
# Wait and collect requests
time.sleep(duration)
# Get collected requests
requests = driver.execute_script("return window.networkRequests;")
# Also get performance entries
performance_entries = driver.execute_script("""
return performance.getEntriesByType('resource').map(entry => ({
name: entry.name,
type: entry.initiatorType,
duration: entry.duration,
size: entry.transferSize,
startTime: entry.startTime
}));
""")
result = {
"intercepted_requests": requests,
"performance_entries": performance_entries,
"total_requests": len(requests) + len(performance_entries)
}
return json.dumps(result, indent=2, default=str)
except Exception as e:
logger.error(f"Error in monitor_network_requests: {e}")
return f"Error: {e}"
finally:
cleanup_driver(driver, use_persistent)
def get_console_logs(url: str, use_persistent: bool = False) -> str:
"""Capture browser console logs"""
driver = None
try:
driver = get_driver(None, use_persistent)
# Inject console log capture before navigation
driver.execute_script("""
window.consoleLogs = [];
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
console.log = function(...args) {
window.consoleLogs.push({
type: 'log',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalLog.apply(console, args);
};
console.error = function(...args) {
window.consoleLogs.push({
type: 'error',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalError.apply(console, args);
};
console.warn = function(...args) {
window.consoleLogs.push({
type: 'warn',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalWarn.apply(console, args);
};
""")
# Navigate to page
driver.get(url)
time.sleep(3) # Wait for logs
# Get captured logs
logs = driver.execute_script("return window.consoleLogs;")
return json.dumps(logs, indent=2, default=str)
except Exception as e:
logger.error(f"Error in get_console_logs: {e}")
return f"Error: {e}"
finally:
cleanup_driver(driver, use_persistent) |