整体思路:
因为selenium不支持带用户名密码验证的代理方式,所以这里借助插件来完成代理的授权验证,做法:
1、创建包含background.js和manifest.json的zip文件
2、在代码中设置插件启动
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "YOU_PROXY_ADDRESS",
port: parseInt(YOUR_PROXY_PORT)
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_PROXY_USERNAME",
password: "YOUR_PROXY_PASSWORD"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: [""]},
['blocking']
);
注意:配置你自己的代理账号密码,我这里用的是阿布云代理,Don't forget to replace YOUR_PROXY_* to your settings.
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
/**
* 取得一个空闲的WebDriver.
*
* @param queueName 队列名称
* @return
*/
public static WebDriver getOneFreeDriver(String queueName, boolean useProxy) throws IOException {
// 从队列里取
WebDriver driver = driverQueue.poll(queueName);
// 一、取到,直接返回
if (null != driver) {
return driver;
}
//二、未取到,创建
//创建ChromeDriverService
ChromeDriverService service = createChromeDriverService();
//不使用代理
if (!useProxy) {
//创建driver返回
return new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome());
}
//使用代理插件动态切换代理
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("D:\\proxy.zip"));
return new RemoteWebDriver(service.getUrl(), chromeOptions);
}
主要是这几句:
//使用代理插件动态切换代理
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("D:\\proxy.zip"));
return new RemoteWebDriver(service.getUrl(), chromeOptions);
org.openqa.selenium.WebDriverException: unknown error: cannot process extension #1
from unknown error: cannot read manifest
请移步我的另外一篇博客:https://blog.csdn.net/hanxue6898/article/details/81453279中有解决办法!!!