Selenium Java:登录后获取Network标签中JS文件大小并验证阈值
实现方案说明
你需求的场景完全可以实现,下面提供两种基于Java+Selenium的可行方案:
方案一:使用Chrome DevTools Protocol(CDP)捕获网络请求(推荐)
这是最精准的方式,能直接获取和Chrome DevTools Network标签一致的文件大小数据,步骤如下:
- 初始化ChromeDriver时,配置启用CDP的Network监听
- 执行登录流程(打开URL、输入账号密码、点击登录)
- 等待页面完全加载后,获取所有已完成的网络请求
- 过滤出匹配
vendor*.js和client*.js的请求,提取响应大小并验证
Java代码示例
import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.devtools.DevTools; import org.openqa.selenium.devtools.v125.network.Network; import org.openqa.selenium.devtools.v125.network.model.Response; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class JsSizeValidator { public static void main(String[] args) { // 配置Chrome选项,禁用缓存确保获取真实文件大小 ChromeOptions options = new ChromeOptions(); options.addArguments("--disable-cache"); ChromeDriver driver = new ChromeDriver(options); DevTools devTools = driver.getDevTools(); devTools.createSession(); // 存储符合条件的响应信息 List<Response> targetResponses = new ArrayList<>(); // 监听Network.responseReceived事件,捕获响应数据 devTools.addListener(Network.responseReceived(), responseReceived -> { Response response = responseReceived.getResponse(); String url = response.getUrl(); // 匹配vendor*.js和client*.js if (url.matches(".*/vendor.*\\.js$") || url.matches(".*/client.*\\.js$")) { targetResponses.add(response); } }); // 启用Network监听 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty())); // 执行登录流程 driver.get("你的目标应用URL"); driver.findElement(By.id("username")).sendKeys("你的用户名"); driver.findElement(By.id("password")).sendKeys("你的密码"); driver.findElement(By.id("submitBtn")).click(); // 等待页面完全加载(可根据实际页面调整等待条件) new WebDriverWait(driver, Duration.ofSeconds(10)) .until(webDriver -> "complete".equals(((JavascriptExecutor) webDriver).executeScript("return document.readyState"))); // 验证文件大小 for (Response res : targetResponses) { long size = res.getHeaders().get("Content-Length") != null ? Long.parseLong(res.getHeaders().get("Content-Length")) : res.getBodySize(); String url = res.getUrl(); if (url.contains("vendor")) { // 验证vendor*.js不超过2MB(2*1024*1024字节) if (size > 2 * 1024 * 1024) { System.out.println("不符合要求:" + url + " 大小为 " + (size/(1024*1024)) + "MB"); } else { System.out.println("符合要求:" + url + " 大小为 " + (size/(1024*1024)) + "MB"); } } else if (url.contains("client")) { // 验证client*.js不超过500KB(500*1024字节) if (size > 500 * 1024) { System.out.println("不符合要求:" + url + " 大小为 " + (size/1024) + "KB"); } else { System.out.println("符合要求:" + url + " 大小为 " + (size/1024) + "KB"); } } } driver.quit(); } }
方案二:使用Javascript Executor读取Performance API数据
通过浏览器的window.performance.getEntries()获取已加载资源的信息,这种方式无需依赖CDP,实现更轻便,但需注意部分浏览器对Performance API的支持细节:
Java代码示例
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.List; import java.util.Map; public class JsSizeValidatorViaJS { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); // 执行登录流程 driver.get("你的目标应用URL"); driver.findElement(By.id("username")).sendKeys("你的用户名"); driver.findElement(By.id("password")).sendKeys("你的密码"); driver.findElement(By.id("submitBtn")).click(); // 等待页面完全加载 new WebDriverWait(driver, Duration.ofSeconds(10)) .until(webDriver -> "complete".equals(((JavascriptExecutor) webDriver).executeScript("return document.readyState"))); // 执行JS获取资源信息 String jsScript = "return window.performance.getEntries().filter(entry => " + "(entry.name.includes('vendor') && entry.name.endsWith('.js')) || " + "(entry.name.includes('client') && entry.name.endsWith('.js'))).map(entry => ({url: entry.name, size: entry.transferSize}));"; List<Map<String, Object>> resources = (List<Map<String, Object>>) ((JavascriptExecutor) driver).executeScript(jsScript); // 验证大小 for (Map<String, Object> res : resources) { String url = (String) res.get("url"); long size = ((Number) res.get("size")).longValue(); if (url.contains("vendor")) { if (size > 2 * 1024 * 1024) { System.out.println("不符合要求:" + url + " 大小为 " + (size/(1024*1024)) + "MB"); } else { System.out.println("符合要求:" + url + " 大小为 " + (size/(1024*1024)) + "MB"); } } else if (url.contains("client")) { if (size > 500 * 1024) { System.out.println("不符合要求:" + url + " 大小为 " + (size/1024) + "KB"); } else { System.out.println("符合要求:" + url + " 大小为 " + (size/1024) + "KB"); } } } driver.quit(); } }
注意事项
- 等待页面加载:必须确保页面完全加载后再获取资源数据,避免遗漏请求;可根据页面实际情况调整等待条件(比如等待某个核心元素出现)
- 单位转换:代码中使用字节转MB/KB,注意
1MB=1024*1024字节,1KB=1024字节 - 缓存问题:如果需要获取真实的文件大小,建议禁用浏览器缓存(如方案一中的
--disable-cache参数),避免读取缓存中的旧数据 - CDP版本:代码中使用的是v125版本的CDP,需确保你的ChromeDriver版本与Chrome浏览器版本匹配
内容的提问来源于stack exchange,提问作者wheelerlc64
相关产品推荐
相关产品推荐

