2017-04-12 206 views
4

我使用HtmlAgilityPack來處理html頁面。 以前我這樣做:使用HtmlAgilityPack.NETCore獲取網頁

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

,但現在我需要使用HtmlAgilityPack.NETCore其中HtmlWeb不存在。 我應該用什麼來代替HtmlWeb才能得到相同的結果?

回答

4

使用HttpClient作爲通過http與遠程資源進行交互的新方式。

至於你的解決方案,你可能需要使用這裏的async方法來非阻塞你的線程,而不是使用.Result。還要注意的是HttpClient was meant to be used from different threads從.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.... 
    } 
} 

大文章關於異步/ AWAIT:Async/Await - Best Practices in Asynchronous Programming由@StephenCleary | 2013年3月

+0

謝謝,這是一個很好的建議。 – AlexCOM

-1

您可以使用HttpClient獲取頁面的內容。

+0

我正在尋找,但找不到。你能告訴我如何使用它? – AlexCOM

+0

你是不是這個意思? 'WebClient client = new WebClient(); client.DownloadFile(url,path);' 我想在不保存的情況下使用文件。 – AlexCOM

1

我寫了這個,它的工作。這是解決我的問題的好方法嗎?

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.... 
     } 
    } 
} 
+0

在答案中加了一些代碼 – VMAtm

+0

這對我很有趣。爲什麼我們不能使用await:client.GetAsync(url) – alerya

3

我在使用netcoreapp1.0的Visual Studio代碼中遇到了同樣的問題。 代之以使用HtmlAgilityPack版本1.5.0-beta5結束。

Remenber:

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']");