簡體   English   中英

如何在 c# selenium chrome 驅動程序中驗證(用戶/密碼)代理

[英]How to authenticate (user/password) proxy in c# selenium chrome driver

我有一個需要使用用戶名和密碼進行身份驗證的 HTTP/HTTPS 代理。 我如何使用 C# selenium chrome webdriver 做到這一點?

string host = proxies[count].Split(':')[0];
int port = Convert.ToInt32(proxies[count].Split(':')[1]) + 1;

string prox = host + ":" + port.ToString();

OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy = prox;
proxy.SslProxy = prox;
options.Proxy = proxy;

options 是我分配給驅動程序的 ChromeOptions 類。

我發現的唯一成功方法是使用 AutoIT ( https://www.autoitscript.com/site/autoit )。

我已經為所有主要瀏覽器設置了代理身份驗證,但這應該適用於 Chrome。 這是我憑記憶在手機上寫的。 如果它不起作用,請告訴我,我會糾正。

WinWait("data:, - Google Chrome","","10")
If WinExists("data:, - Google Chrome","")Then
WinActivate("data:, - Google Chrome")
Send("USERNAMEGOESHERE"{TAB}")
Send("USERPASSWORDGOESHERE"{ENTER}")

使用 AutoIT,將其創建為腳本,將其編譯為 exe,將其保存在某處並使用以下(Java 代碼)引用該文件:

Runtime.getRuntime().exec("C:\\users\\USERID\\desktop\\FILENAME.exe");

我發現最好在調用觸發代理身份驗證的 URL 之前調用代理腳本一個步驟。

這是針對 Firefox 的,但最重要的答案可能會有所幫助。

C# Selenium WebDriver FireFox Profile - 使用代理和身份驗證

您可以做的是創建一個配置文件並將身份驗證數據保存在其中。 如果您的配置文件名為“webdriver”,您可以在初始化時從您的代碼中選擇它:

ProfilesIni allProfiles = new ProfilesIni(); 
FirefoxProfile profile = allProfiles.getProfile("WebDriver"); 
profile.setPreferences("foo.bar",23);
WebDriver driver = new FirefoxDriver(profile);

2019年更新

在多次不幸的嘗試之后,最簡單的解決方案是為 Chrome 創建一個擴展程序,正如 Mike 在這篇文章中所解釋的那樣。

這聽起來很奇怪,但實際上非常簡單。

2021 更新

我創建了一個簡單的庫( nuget 包),可以幫助您進行 selenium 代理身份驗證。 你可以在Github repo 上查看源代碼。 它也適用於使用無頭驅動程序。

用法:

public void Test()
{  
    // Create a local proxy server
    var proxyServer = new SeleniumProxyAuth();

    // Don't await, have multiple drivers at once using the local proxy server
    TestSeleniumProxyServer(proxyServer, new ProxyAuth("123.123.123.123", 80, "prox-username1", "proxy-password1"));
    TestSeleniumProxyServer(proxyServer, new ProxyAuth("11.22.33.44", 80, "prox-username2", "proxy-password2"));
    TestSeleniumProxyServer(proxyServer, new ProxyAuth("111.222.222.111", 80, "prox-username3", "proxy-password3"));

    while (true) { }
}

private async Task TestSeleniumProxyServer(SeleniumProxyAuth proxyServer, ProxyAuth auth)
{
    // Add a new local proxy server endpoint
    var localPort = proxyServer.AddEndpoint(auth);

    ChromeOptions options = new ChromeOptions();
    //options1.AddArguments("headless");

    // Configure the driver's proxy server to the local endpoint port
    options.AddArgument($"--proxy-server=127.0.0.1:{localPort}");

    // Optional
    var service = ChromeDriverService.CreateDefaultService();
    service.HideCommandPromptWindow = true;

    // Create the driver
    var driver = new ChromeDriver(service, options);

    // Test if the driver is working correctly
    driver.Navigate().GoToUrl("https://www.myip.com/");
    await Task.Delay(5000);
    driver.Navigate().GoToUrl("https://amibehindaproxy.com/");
    await Task.Delay(5000);

    // Dispose the driver
    driver.Dispose();
}

如今,Chrome 不允許您使用任何擴展程序進行 selenium Web 測試。 並且 selenium 沒有任何內置的用戶名和密碼輸入代理。

我找到的唯一解決方案是使用 AutoIt。 它將自動執行 Windows 級別的操作。 雖然 selenium 只自動化瀏覽器級別的操作。

將用戶名和密碼傳遞給代理對話框是一個 WINDOWS 級別的操作。

要下載並安裝 AutoIt,您可以訪問: https : //www.guru99.com/use-autoit-selenium.html

我寫了一個簡單的 AutoIt 腳本如下:

; option to read substring in a window title
Opt("WinTitleMatchMode", 2)

; wait for proxy username & password dialog box
WinWait("- Google Chrome","","10")

; if the box shows up, write the username and password
; username & password are passed as program parameters
If WinExists("- Google Chrome","") Then
    WinActivate("- Google Chrome")

    ; $CmdLine is a special array that holds parameters
    if $CmdLine[0] = 2 Then
        Send($CmdLine[1] & "{TAB}")
        Send($CmdLine[2] & "{ENTER}")
    EndIf

    ; any request dialog to save credential?
    WinWait("Save password for ","","10")

    ; if any, close it
    If WinExists("Save password for ","") Then
        WinActivate("Save password for ")
        Send("{TAB}")
        Send("{SPACE}")
    EndIf
EndIf

Exit

將腳本編譯為可執行程序,如ProxyAuth.exe

程序將接收兩個參數:用戶名和密碼。 通過參數,您可以在 C# 腳本中使用動態用戶名和密碼。

然后你需要在 C# 代碼中使用該程序,如下所示:

ChromeOptions ChromeOptions = new ChromeOptions();

Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");

Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);

string cmd = string.Format($"{ProxyUsername} {ProxyPassword}");
Process proc = new Process();
proc.StartInfo.FileName = "ProxyAuth.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;

proc.Start();

您將需要使用OpenQA.SeleniumOpenQA.Selenium.ChromeSystem.Diagnostics命名空間。

**編輯**

如果您對使用 AutoIt 感興趣,也可以在 NuGet 中使用他們的庫。 只需在“管理 NuGet 包”中搜索:AutoIt。 選擇顯示的唯一一個 AutoIt 包並安裝它。

使用此庫,您無需如上所述創建ProxyAuth.exe應用程序。

您可以使用 AutoIt 庫並在 C# 代碼中進行修改:

ChromeOptions ChromeOptions = new ChromeOptions();

Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = $"{ProxyIP}:{ProxyPort}";
proxy.HttpProxy = $"{ProxyIP}:{ProxyPort}";
ChromeOptions.Proxy = proxy;
ChromeOptions.AddArgument("ignore-certificate-errors");

Driver = new ChromeDriver(ChromeOptions);
Driver.Navigate().GoToUrl(Url);

// use the AutoIt library
AutoItX.AutoItSetOption("WinTitleMatchMode", 2);

AutoItX.WinWaitActive("- Google Chrome", "", 10);
AutoItX.WinActivate("- Google Chrome");

AutoItX.Send(ProxyUsername);
AutoItX.Send("{TAB}");
AutoItX.Send(ProxyPassword);
AutoItX.Send("{ENTER}");

// dismiss save password prompt
AutoItX.WinWaitActive("Save password for ", "", 10);
AutoItX.WinActivate("Save password for ");

AutoItX.Send("{TAB}");
AutoItX.Send("{SPACE}");

我為你的問題創建了一個小包( https://github.com/RDavydenko/OpenQA.Selenium.Chrome.ChromeDriverExtensions

安裝包:

Install-Package OpenQA.Selenium.Chrome.ChromeDriverExtensions -Version 1.2.0

用於您的ChromeOptions

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
...
var options = new ChromeOptions();

// Add your HTTP-Proxy
options.AddHttpProxy(PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD);

var driver = new ChromeDriver(options); // or new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory, options);

driver.Navigate().GoToUrl("https://whatismyipaddress.com/"); // Check your IP

使用代理的參數代替PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASSWORD

在另一個線程C# Selenium Proxy Authentication with Chrome Driver 中回答。

主要思想 - 使用Selenium 4.0 和 BiDi API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM