首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C#中处理HTTP响应的框架

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

Stack Overflow用户
提问于 2020-06-30 21:50:52
回答 2查看 91关注 0票数 1

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

上一次我做类似的事情时,我使用了WatiN和HTMLAgilityPack。但WatiN并不是很优雅,因为它打开了一个浏览器窗口来与网站进行交互。它更多地是为集成测试而设计的,但它仍然完成了这项工作。

这一次,我使用AngleSharp来解析超文本标记语言,但我仍然需要编写代码来登录网站,按下几个按钮并发布一些帖子。

有没有什么框架可以让这一切变得简单明了?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-01 02:35:46

嗯-看起来我低估了AngleSharp的力量

有一个很棒的帖子here,描述了如何使用它来登录网站和张贴表单。

自那以后,该库进行了更新,因此有一些事情发生了变化,但功能和方法都是相同的。我将在这里包含我的“测试”代码,它演示了可用性。

代码语言:javascript
运行
复制
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。然后,上面的代码变成

代码语言:javascript
运行
复制
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"
            });
票数 1
EN

Stack Overflow用户

发布于 2020-06-30 22:14:53

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

Selenium.WebDriver NuGet Package

C# Tutorial 1

C# Tutorial 2

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62659008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档