简体   繁体   中英

C# Selenium - How to use proxy with Authentication?

I've been struggling for two days and couldn't find a solution. I tried it first with mozilla firefox. Then I tried with google chrome and got the same error again. How do I add the proxy feature to the browser? More precisely, how can I run it by adding user properties?

It gets stuck when it comes to .networkInterceptor.StartMonitoring()" code. The browser opens but the page does not load.

If I enter the link manually after the browser opens, it requires username and password.

Note: Also, is there a different method?

Version: Selenium Webdriver 4.0.0

Codes:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

private async void Create()
{
    Proxy proxy = new Proxy();
    var proxyAddress = "host:port";
    proxy.HttpProxy = proxyAddress;
    proxy.SslProxy = proxyAddress;

    ChromeOptions options = new ChromeOptions();
    options.Proxy = proxy;

    IWebDriver driver = new ChromeDriver(options);

    NetworkAuthenticationHandler handler = new NetworkAuthenticationHandler()
    {
        UriMatcher = (d) => true,
        Credentials = new PasswordCredentials("user", "password")
    };

    INetwork networkInterceptor = driver.Manage().Network;
    networkInterceptor.AddAuthenticationHandler(handler);
    await networkInterceptor.StartMonitoring();

    driver.Navigate().GoToUrl("www.google.com");

    await networkInterceptor.StopMonitoring();
}

I think that the question must become: why selenium's method: await.networkInterceptor.StartMonitoring(); doesn't work on windows forms. This occurs because windows forms is single threaded application. So in order to make it to work you might call the create method as below:

//First change your `Create()` method to return a Task instead of void.
private async void button1_Click(object sender, EventArgs e)
{
    await Task.Run(async () =>
    {
        await Create();
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM