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

如何覆盖 selenium2 chrome 驱动程序中的基本身份验证?我在我的项目中遇到了一个问题,其中 chrome 需要身份验证"弹出窗口正在阻止 webdriver 继续导航.请找到所附的屏幕截图.我正在使用以下代码来实例化 chrome 驱动程序,

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. I am using following code to instantiate chrome driver,

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();
}

你能帮忙吗-

谢谢,

推荐答案

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

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!).

这是 Chrome 和 Python 的工作原理:

Here is how it works for Chrome and Python:

  1. 创建一个包含两个文件的 zip 文件 proxy.zip:

background.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']
);

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

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

ma​​nifest.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. 将创建的 proxy.zip 添加为扩展名

  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()

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

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

相关文章