[英]Get web page using HtmlAgilityPack.NETCore
我使用HtmlAgilityPack
来处理html页面。 以前我这样做过:
HtmlWeb web = new HtmlWeb();
HtmlDocument document = web.Load(url);
var nodes = document.DocumentNode.SelectNodes("necessary node");
但现在我需要使用没有HtmlWeb
的HtmlAgilityPack.NETCore。 我应该用什么代替HtmlWeb
来获得相同的结果呢?
使用HttpClient
作为通过http与远程资源交互的新方法。
至于你的解决方案,你可能需要在这里使用async
方法来阻止你的线程,而不是.Result
用法。 另请注意, HttpClient
旨在从.Net 4.5开始的不同线程中使用 ,因此您不应每次都重新创建它:
// instance or static variable
HttpClient client = new HttpClient();
// get answer in non-blocking way
using (var response = await client.GetAsync(url))
{
using (var content = response.Content)
{
// read answer in non-blocking way
var result = await content.ReadAsStringAsync();
var document = new HtmlDocument();
document.LoadHtml(result);
var nodes = document.DocumentNode.SelectNodes("Your nodes");
//Some work with page....
}
}
关于async / await的精彩文章: Async / Await - @StephenCleary 进行异步编程的最佳实践 2013年3月
我在使用netcoreapp1.0的Visual Studio代码中遇到了同样的问题。 结束使用HtmlAgilityPack版本1.5.0-beta5。
记得添加:
using HtmlAgilityPack;
using System.Net.Http;
using System.IO;
我是这样做的:
HttpClient hc = new HttpClient();
HttpResponseMessage result = await hc.GetAsync($"http://somewebsite.com");
Stream stream = await result.Content.ReadAsStreamAsync();
HtmlDocument doc = new HtmlDocument();
doc.Load(stream);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='whateverclassyouarelookingfor']");
我写了这个,它正在发挥作用。 这是解决问题的好方法吗?
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
HtmlDocument document = new HtmlDocument();
document.LoadHtml(result);
var nodes = document.DocumentNode.SelectNodes("Your nodes");
//Some work with page....
}
}
}
您可以使用HttpClient来获取页面的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.