selenium获取网页性能和资源加载的监控数据

tone 1693 2024-10-28
  • 在selenium执行自动化测试时,将网页性能和资源加载的监控数据附加在测试报告里能更好的了解测试过程中的详情
  • selenium4.0支持cdp协议可以直接和浏览器内核提供的api进行交互,效率更高,但是没有执行js灵活和全面,chrome详细cdp命令https://chromedevtools.github.io/devtools-protocol/
    # 1. 获取页面的性能数据
    performance_data = self.driver.execute_script("return window.performance.getEntriesByType('navigation')[0]")
    
    # 2. 计算各项时间
    navigation_start = performance_data['startTime']
    dom_content_loaded = performance_data['domContentLoadedEventEnd'] - navigation_start
    page_load_time = performance_data['loadEventEnd'] - navigation_start
    white_screen_time = performance_data['responseStart'] - navigation_start
    
    print(f"DOM内容加载时间: {dom_content_loaded}ms")
    print(f"页面加载时间: {page_load_time}ms")
    print(f"白屏时间: {white_screen_time}ms")
    
    # 3. 获取资源信息
    resources = self.driver.execute_script("return window.performance.getEntriesByType('resource')")
    initiator_types = [resource["initiatorType"] for resource in resources]
    type_temp = Counter(initiator_types)
    print(type_temp)
    
    # 4. 获取详细的网络时间信息
    dns_time = performance_data['domainLookupEnd'] - performance_data['domainLookupStart']
    tcp_time = performance_data['connectEnd'] - performance_data['connectStart']
    request_time = performance_data['responseStart'] - performance_data['requestStart']
    dom_time = performance_data['domComplete'] - performance_data['domInteractive']
    
    print(f"DNS查询时间: {dns_time}ms")
    print(f"TCP连接时间: {tcp_time}ms")
    print(f"Request时间: {request_time}ms")
    print(f"DOM加载时间: {dom_time}ms")
    
    # 5. 获取 JS 堆内存使用量
    memory_info = self.driver.execute_script("""
      return {
        usedJSHeapSize: window.performance.memory.usedJSHeapSize / (1024 * 1024),  // 转换为MB
        totalJSHeapSize: window.performance.memory.totalJSHeapSize / (1024 * 1024) // 转换为MB
      };
    """)
    js_heap_size = memory_info.get('usedJSHeapSize', 0)
    print(f"JS堆内存使用量: {js_heap_size:.2f} MB")
    
    # 6. 页面内存使用情况
    used_js_heap_size = self.driver.execute_script("""
      return window.performance.memory.usedJSHeapSize / (1024 * 1024);  // 转换为MB
    """)
    print(f"内存使用情况: {used_js_heap_size:.2f} MB")
    

Snipaste_2024-10-28_13-39-21.png