简体   繁体   English

C# Selenium - 如何使用带身份验证的代理?

[英]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.我先用 mozilla firefox 试了一下。然后我用 google chrome 试了一下,又出现了同样的错误。 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.当涉及到 .networkInterceptor.StartMonitoring()" 代码时,它会卡住。浏览器打开但页面未加载。

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版本: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();我认为问题必须变成:为什么 selenium 的方法: await.networkInterceptor.StartMonitoring(); doesn't work on windows forms. This occurs because windows forms is single threaded application.不适用于 windows forms。发生这种情况是因为 windows forms 是单线程应用程序。 So in order to make it to work you might call the create method as below:因此,为了使其正常工作,您可以按如下方式调用 create 方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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