使用 HtmlAgilityPack.NETCore 获取网页

Get web page using HtmlAgilityPack.NETCore

我使用 HtmlAgilityPack 来处理 html 页面。 以前我这样做过:

HtmlWeb web = new HtmlWeb();
HtmlDocument document = web.Load(url);
var nodes = document.DocumentNode.SelectNodes("necessary node");

但现在我需要使用 HtmlAgilityPack.NETCore,其中缺少 HtmlWeb。 我应该使用什么 HtmlWeb 来获得相同的结果?

您可以使用HttpClient获取页面内容。

我写了这个并且它正在运行。这是解决我问题的好方法吗?

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 作为通过 http 与远程资源交互的新方式。

至于您的解决方案,您可能需要使用此处的 async 方法来非阻塞您的线程,而不是 .Result 用法。另请注意, 从 .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 - Best Practices in Asynchronous Programming @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']");