我正在尝试使用 Google Chrome 运行 Selenium 测试。我希望使用 HTTP 基本身份验证登录。这在 Selenium 中没有实现,所以建议加载一个扩展。我正在使用来自
的代码https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy和 the answer to "How to override basic authentication in selenium2 with Java using chrome driver?"
我已尝试使其适应我的需要。
更新
检查最小工作示例。
git clone git@github.com:alexbiddle/selenium-chrome-http-basic-auth.git
摘录如下
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "https",
host: "subdomain.example.com"
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "example",
password: "abc123"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
使用 Java 加载它
ChromeOptions chromeOptions = new ChromeOptions();
File proxyPath = new ClassPathResource("proxy.zip").getFile();
chromeOptions.addExtensions(proxyPath);
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CAPABILITY, chromeOptions);
webDriver = new ChromeDriver(capability);
我在 https://developer.chrome.com/extensions/proxy#type-ProxyServer 仔细检查了文档以防万一缺少某些值,但是在使用 URL 加载测试时
https://subdomain.example.com
它失败了
ERR_TUNNEL_CONNECTION_FAILED
我在 Mac 上使用 Chrome。
最佳答案
错误可能是由于您的扩展程序定义的代理造成的。
如果您需要与系统不同的代理,您应该在没有代理的情况下构建扩展并在功能中定义代理。
要创建扩展,只需使用您在 username
和 password
中定义的凭据压缩以下文件:
list .json:
{
"manifest_version": 2,
"name": "Authentication for ...",
"version": "1.0.0",
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking"],
"background": {
"scripts": ["background.js"]
}
}
background.js :
var username = "my-username";
var password = "my-password";
chrome.webRequest.onAuthRequired.addListener(
function handler(details) {
if (username == null)
return {cancel: true};
var authCredentials = {username:username, password: username};
username = password = null;
return {authCredentials: authCredentials};
},
{urls: ["<all_urls>"]},
['blocking']
);
关于java - 为 Selenium 创建 HTTP Basic auth Chrome 扩展(MWE 可用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458165/