关于java selenium使用阿布云,官网也只有火狐的示例代码而谷歌浏览器的示例根本没有,网上能找到一两篇文章,基本不能使用或许自己根本没有试过。
今天这篇博客来分享一下java selenium如何使用阿布云代理,核心思路就是selenium不支持用户名加密码的这种ip代码方式。想要使用谷歌浏览器驱动的代理,用到了谷歌浏览器的插件脚本方式让代理生效。
java代码如下
package com.watchmen.selenium;
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/**
*
* @author kk
* @Description selenium使用阿布云代理
*/
public class ChromeDriverProxy {
public static void main(String[] args) {
try {
// 加载驱动(例如:C:\\chromedriver.exe)
System.setProperty("webdriver.chrome.driver", "浏览器驱动存放路径");
// 设置浏览器参数
ChromeOptions options = new ChromeOptions();
// ip代理(例如:C:\\proxy.zip)
options.addExtensions(new File("插件脚本存放的路径"));
// 创建驱动对象
WebDriver driver = new ChromeDriver(options);
// 使用ip138验证代理是否生效
driver.get("https://www.ip138.com/");
} catch (Exception e) {
e.printStackTrace();
}
}
}
谷歌浏览器脚本
创建名为:manifest.json的文件内容如下
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
}
}
在创建名为background.js的文件内容如下
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "http-dyn.abuyun.com", // 阿布云代理地址
port: 9020 // 端口
}
}
}
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "xxxxxx", // 阿布云账号
password: "xxxxxx" // 阿布云密码
}
}
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
)
创建完这两个文件后将这两个文件打包成一个zip文件
运行效果如下图
可以看到ip每次都变,代码已经在码云上了地址是:https://gitee.com/yankangkk/watchmen/tree/master/src/main/java/com/watchmen/selenium
谷歌浏览器驱动和proxy.zip也在码云上地址是:https://gitee.com/yankangkk/watchmen/tree/master/src/main/resources/selenium