在 C# 中处理 HTTP 响应的框架

Framework for handling HTTP responses in C#

该项目是一个与网页交互的 C# 桌面应用程序。

上次我做这样的事情时,我使用了 WatiN 和 HTMLAgilityPack。但是 WatiN 不是很优雅,因为它会打开浏览器 window 与网站进行交互。它更专为集成测试而设计,但它仍然完成了工作。

这次我正在查看 AngleSharp 来解析 HTML,但我仍然需要编写代码来登录网站、按下几个按钮并执行一些 POSTS。

有没有我可以使用的框架来使这个简单明了?

如果您想与网站交互、填写文本框、单击按钮等,我认为更合乎逻辑的解决方案是使用和管理实际的网络浏览器。

Selenium.WebDriver NuGet Package

C# Tutorial 1

C# Tutorial 2

嗯 - 看来我低估了 AngleSharp 的威力

有一个很棒的 post here 描述了如何使用它登录网站和 post 表单。

此库已更新,因此发生了一些变化,但功能和方法是相同的。 我将在此处包含我的“测试”代码以演示可用性。

public async Task LogIn()
        {
            //Sets up the context to preserve state from one request to the next
            var configuration = Configuration.Default.WithDefaultLoader().WithDefaultCookies();
            var context = BrowsingContext.New(configuration);

            /Loads the login page   
            await context.OpenAsync("https://my.website.com/login/");

            //Identifies the only form on the page (can use CSS selectors to choose one if multiple), fills in the fields and submits
            await context.Active.QuerySelector<IHtmlFormElement>("form").SubmitAsync(new
            {
                username = "CharlieChaplin",
                pass = "x78gjdngmf"
            });
            
            //stores the response page body in the result variable.   
            var result = context.Active.Body;

编辑 - 在使用它一段时间后,我发现 Anglesharp.IO 中有一个更强大的 HttpRequester。上面的代码就变成了

public async Task LogIn()
        {
            var client = new HttpClient();
            var requester = new HttpClientRequester(client);
            //Sets up the context to preserve state from one request to the next
            var configuration = Configuration.Default
                               .WithRequester(requester)
                               .WithDefaultLoader()
                               .WithDefaultCookies();

            var context = BrowsingContext.New(configuration);

            /Loads the login page   
            await context.OpenAsync("https://my.website.com/login/");

            //Identifies the only form on the page (can use CSS selectors to choose one if multiple), fills in the fields and submits
            await context.Active.QuerySelector<IHtmlFormElement>("form").SubmitAsync(new
            {
                username = "CharlieChaplin",
                pass = "x78gjdngmf"
            });