使用Selenium-Java进行网络连接节流



我一直在尝试根据本文中的片段使用Selenium WebDriver实现网络节流。https://stackoverflow.com/a/56526094/2122388

从上面的链接重新张贴代码:

protected void networkThrotting() throws IOException {
Map map = new HashMap();
map.put("offline", false);
map.put("latency", 5);
map.put("download_throughput", 500);
map.put("upload_throughput", 1024);
CommandExecutor executor = ((ChromeDriver)driver).getCommandExecutor();
Response response = executor.execute(
new Command(((ChromeDriver)driver).getSessionId(), "setNetworkConditions", ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map)))
);
}

它像org.openqa.selenium.UnsupportedCommandException: setNetworkConditions一样抛出异常。经过调试,发现AbstractHttpCommandCodec中没有setNetworkConditions的定义,但找到了setNetworkConnection。SO尝试更改如下:

protected void networkThrotting() throws IOException {
Map map = new HashMap();
map.put("offline", false);
map.put("latency", 5);
map.put("download_throughput", 500);
map.put("upload_throughput", 1024);

CommandExecutor executor = ((ChromeDriver)driver).getCommandExecutor();
Response response = executor.execute(
new Command(((ChromeDriver)driver).getSessionId(), "setNetworkConnection", ImmutableMap.of("network_connection", ImmutableMap.copyOf(map)))
);
}

它不会抛出任何异常并让测试通过,但网络速度没有预期的变化。我使用的是Selenium 3.x和Chrome 100.x

因此,我们非常感谢您在这里提供的任何意见。

如果有其他人因为同样的问题在这里,那么下面是我在最后找到的解决方案:

  1. 升级到Selenium-4.x并使用DevTools可以让事情变得更加简单明了
  2. 使用BrowserMob代理并四处游玩

我选择了Option-2来实现网络节流,因为我在将Selenium版本升级到4.x时有一些限制(但升级Selenium版是非常简单的解决方案(

这里有一个工作示例,可以帮助其他人了解如何在DevTools中使用Selenium-4.x版本。

try (DevTools devTools = ((ChromeDriver) driver).getDevTools()) {
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
// network offline
devTools.send(Network.emulateNetworkConditions(true, 0, 0, 0, Optional.of(ConnectionType.WIFI)));
// Your offline code puts here.
}
// Your online code puts here, if any.

注意:您的Chrome驱动程序版本应该与Selenium Devtools版本匹配,例如

'org.seleniumhq.selenium:selenium-devtools-vNN:SELENIUM_VERSION'

vNN是您的chrome版本,类似于硒开发工具-v111:4.8.3硒版本。

最新更新