如何使用 chrome 驱动程序使用 Java 覆盖 selenium2 中的基本身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9888323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:47:27  来源:igfitidea点击:

How to override basic authentication in selenium2 with Java using chrome driver?

javagoogle-chromeseleniumselenium-webdriverselenium-chromedriver

提问by ABCDEFG

How to override basic authentication in selenium2 chrome driver? I am facing an issue in my project where chrome "Authentication required" popup is coming which is blocking webdriver to continue navigation. Please find the attached screenshot for the same. enter image description hereI am using following code to instantiate chrome driver,

如何覆盖 selenium2 chrome 驱动程序中的基本身份验证?我在我的项目中遇到了一个问题,即 chrome“需要身份验证”弹出窗口即将出现,这阻止了 webdriver 继续导航。请找到相同的附加屏幕截图。 在此处输入图片说明我正在使用以下代码来实例化 chrome 驱动程序,

private WebDriver driver;
@Override
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("webdriver.chrome.driver", "C:/Selenium/chromedriver.exe");
    driver = new ChromeDriver();
}
@Override
protected void tearDown() throws Exception {
    // TODO Auto-generated method stub
    super.tearDown();
}

Could you please help -

能否请你帮忙 -

Thanks,

谢谢,

回答by Mike

I've struggled with the same problem over an hour and finally @kenorb's solution rescued me. To be short you need to add a browser extension that does the authentication for you (since Selenium itself can't do that!).

我在一个多小时内遇到了同样的问题,最后@kenorb 的解决方案救了我。简而言之,您需要添加一个浏览器扩展来为您进行身份验证(因为 Selenium 本身无法做到这一点!)。

Here is how it works for Chromeand Python:

以下是ChromePython 的工作原理:

  1. Create a zip file proxy.zipcontaining two files:
  1. 创建一个包含两个文件的 zip 文件proxy.zip

background.js

背景.js

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: ["<all_urls>"]},
        ['blocking']
);

Don't forget to replace YOUR_PROXY_*to your settings.

不要忘记将YOUR_PROXY_*替换为您的设置。

manifest.json

清单文件.json

{
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "Chrome Proxy",
    "permissions": [
        "proxy",
        "tabs",
        "unlimitedStorage",
        "storage",
        "<all_urls>",
        "webRequest",
        "webRequestBlocking"
    ],
    "background": {
        "scripts": ["background.js"]
    },
    "minimum_chrome_version":"22.0.0"
}
  1. Add the created proxy.zip as an extension

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_extension("proxy.zip")
    
    driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
    driver.get("http://google.com")
    driver.close()
    
  1. 添加创建的 proxy.zip 作为扩展

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_extension("proxy.zip")
    
    driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
    driver.get("http://google.com")
    driver.close()
    

That's it. For me that worked like a charm. If you need to create proxy.zip dynamically or need PHP example then go to the original post

而已。对我来说,这就像一个魅力。如果您需要动态创建 proxy.zip 或需要 PHP 示例,请转到原始帖子

回答by Rohit

I think you're talking about using NTLM Authentication(windows integrated authentication) not Basic Authentication(where you provider your credentials in URL). Assuming that here is what you can try for running NTML auth in chrome:

我认为您在谈论使用NTLM 身份验证Windows 集成身份验证)而不是基本身份验证您在 URL 中提供凭据)。假设您可以尝试在 chrome 中运行 NTML 身份验证:

Approach 1

方法一

Go to Internet Explorer, and open "Internet Options". Follow following steps:

转到 Internet Explorer,然后打开“Internet 选项”。请按照以下步骤操作:

  • Add your site to either Local intranet or Trusted sites add
  • List item
  • List item
  • List item
  • List item
  • 将您的站点添加到本地 Intranet 或受信任站点 添加
  • 项目清单
  • 项目清单
  • 项目清单
  • 项目清单

After these changes, your chrome authentication should work. If you're wondering that how IE settings effect chrome behavior then, Chrome uses IE security settings for authentication.

进行这些更改后,您的 chrome 身份验证应该可以工作了。如果您想知道 IE 设置如何影响 Chrome 行为,Chrome 使用 IE 安全设​​置进行身份验证。

Some good resources / credits:

一些好的资源/学分:

  1. Good details
  2. Selenium issue details
  1. 好细节
  2. Selenium 问题详情

Approach 2

方法二

Add your site to Local intranetand don't change anything for user authentication. By default, second option (Automatic logon only in Intranet sites) is selected.

将您的站点添加到本地 Intranet,不要更改任何用户身份验证。默认情况下,选择第二个选项(仅在 Intranet 站点中自动登录)。

回答by kenki

You can try adding the login credentials to the url get request (in Java):

您可以尝试将登录凭据添加到 url get 请求(在 Java 中):

driver.get("http://username:[email protected]/")

回答by Thiago

I manage to do that sending the credentials twice. I don't know why, but in the second time the browser sends the packet, the authentication header goes with basic authentication.

我设法做到了两次发送凭据。我不知道为什么,但是在浏览器第二次发送数据包时,身份验证标头采用基本身份验证。

My code (using C#):

我的代码(使用 C#):

string url = "http://user:[email protected]/";
IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl(url);
webDriver.Url = url;

回答by kenorb

Apart of configuring Network Proxy Preferences, you can set http_proxyin /etc/environment.

除了配置网络代理首选项之外,您还可以http_proxy/etc/environment.

Other method is to use Chrome HTTP Private Proxy(which is based on Chrome-proxy-helper).

另一种方法是使用Chrome HTTP Private Proxy(基于Chrome-proxy-helper)。

Here is PHP example (found in README):

这是 PHP 示例(在 README 中找到):

$pluginForProxyLogin = '/tmp/a'.uniqid().'.zip';

$zip = new ZipArchive();
$res = $zip->open($pluginForProxyLogin, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFile('/path/to/Chrome-proxy-helper/manifest.json', 'manifest.json');
$background = file_get_contents('/path/to/Chrome-proxy-helper/background.js');
$background = str_replace(['%proxy_host', '%proxy_port', '%username', '%password'], ['5.39.64.181', '54991', 'd1g1m00d', '13de02d0e0z9'], $background);
$zip->addFromString('background.js', $background);
$zip->close();

putenv("webdriver.chrome.driver=/path/to/chromedriver");

$options = new ChromeOptions();
$options->addExtensions([$pluginForProxyLogin]);
$caps = DesiredCapabilities::chrome();
$caps->setCapability(ChromeOptions::CAPABILITY, $options);

$driver = ChromeDriver::start($caps);
$driver->get('https://old-linux.com/ip/');

header('Content-Type: image/png');
echo $driver->takeScreenshot();


unlink($pluginForProxyLogin);

The same logic should work for other languages as well.

同样的逻辑也适用于其他语言。

More portable solution is reported already on SeleniumHQ GitHub.

SeleniumHQ GitHub 上已经报告了更便携的解决方案。

See also:

也可以看看: