原创文章,转载请注明原文章地址,谢谢!
方式一:使用HttpCommandExecutor
RemoteWebDriver driver = null;
//remote driver url
URL url = new URL("http://xxx.xxx.xxx.xxx:4444/wd/hub");
//httpclient builder
HttpClientBuilder builder = HttpClientBuilder.create();
//proxy
HttpHost proxy = new HttpHost("xxx.xxx.xxx.xxx", xxxx);
builder.setProxy(proxy);
HttpClient.Factory factory = u -> new ApacheHttpClient(builder.build(), u);
HttpCommandExecutor executor = new HttpCommandExecutor(new HashMap<>(), url, factory);
driver = new RemoteWebDriver(executor, DesiredCapabilities.chrome());
结论:这种方式存在一个问题:实际的请求路径是先通过Proxy代理,再请求RemoteDriver远程请求目的地址。只有当Proxy和RemoteDriver同属一个网络下才能生效,而现实是一般RemoteDriver是内网地址,Proxy是外网,这种场景下不可用。
方式二:使用DesiredCapabilities
String proxyHost = "xxx.xxx.xxx.xxx";
int proxyPort = xxxx;
logger.info("Use proxy host: " + proxyHost + ":" + proxyPort);
URL url = null;
try {
url = new URL("http://172.16.251.113:4444/wd/hub");
} catch (Exception e) {
e.printStackTrace();
}
DesiredCapabilities desiredCapabilities = new DesiredCapabilities(DesiredCapabilities.chrome());
org.openqa.selenium.Proxy pro = new org.openqa.selenium.Proxy();
pro.setHttpProxy(proxyHost + ":" + proxyPort); // http代理
pro.setSslProxy(proxyHost + ":" + proxyPort); // https代理
desiredCapabilities.setCapability(CapabilityType.PROXY, pro);
return new RemoteWebDriver(url, desiredCapabilities);
参考链接:
https://www.it1352.com/965411.html
https://stackoverflow.com/questions/34846014/using-selenium-remotewebdriver-behind-corporate-proxy
博客内容仅供自已学习以及学习过程的记录,如有侵权,请联系我删除,谢谢!
网友评论