selenium执行自动化测试时获取网页性能和资源加载的监控数据

  • 在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")
    

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值