也一直在尝试解决此问题,但 nuget 不适用于 .net 核心。但是 api 仍然是一个 API,因此它也可以从 c# 代码中访问。因此,您可以自己设置代理。我在 powershell 中做了代理启动,但它也可以在 c# 代码中完成。
在github下载BrowserMobProxy https://github.com/lightbody/browsermob-proxy
像这样启动bat文件,powershell e.g: .\browsermob -port 8080
做一些 api 调用。我用的是restsharp:
创建代理实例
var client = new RestClient("http://localhost:8080/proxy");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "text/plain");
var body = @" {""port"":8081}";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
创建 Har 文件,以便开始保存信息:
var client = new RestClient("http://localhost:8080/proxy/8081/har");
client.Timeout = -1;
var request = new RestRequest(Method.PUT);
IRestResponse response = client.Execute(request);
使用以下代码使用 selenium 设置代理:
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = "http://localhost:8081";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
开始测试
driver.Navigate().GoToUrl("https://www.selenium.dev/");
获取 har 文件
var client = new RestClient("http://localhost:8080/proxy/8081/har");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);