该项目是一个与网页交互的C#桌面应用程序。
上一次我做类似的事情时,我使用了WatiN和HTMLAgilityPack。但WatiN并不是很优雅,因为它打开了一个浏览器窗口来与网站进行交互。它更多地是为集成测试而设计的,但它仍然完成了这项工作。
这一次,我使用AngleSharp来解析超文本标记语言,但我仍然需要编写代码来登录网站,按下几个按钮并发布一些帖子。
有没有什么框架可以让这一切变得简单明了?
发布于 2020-07-01 02:35:46
嗯-看起来我低估了AngleSharp的力量
有一个很棒的帖子here,描述了如何使用它来登录网站和张贴表单。
自那以后,该库进行了更新,因此有一些事情发生了变化,但功能和方法都是相同的。我将在这里包含我的“测试”代码,它演示了可用性。
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"
});
发布于 2020-06-30 22:14:53
https://stackoverflow.com/questions/62659008
复制相似问题