2016-09-15 27 views
0

我聽到好東西的HTMLAgilityPack庫,所以我想我會試試看,但我曾與它絕對的零成功。我一直在想這個問題好幾個月。不管我做什麼,我都不能讓這個代碼給我以外的任何其他東西。我試着按照這個例子(http://www.c-sharpcorner.com/uploadfile/9b86d4/getting-started-with-html-agility-pack/),但我沒有得到相同的結果,我不能解釋爲什麼。HTMLAgilityPack的selectNodes總是返回null

我嘗試加載該文件,然後運行的SelectNodes選擇所有超鏈接,但它總是返回一個空列表。我試過選擇各種節點(divs,p,a,所有東西),它總是返回一個空列表。我試過使用doc.Descendants,我試過在本地和網上使用不同的源文件,我做的任何事情都不會返回實際結果。

我一定是忽略了一些重要的東西,但我無法弄清楚它是什麼。我可能會錯過什麼?

代碼:

public string GetSource() 
    { 
     try 
     { 
      string result = ""; 

      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
      if (!System.IO.File.Exists("htmldoc.html")) 
       throw new Exception("Unable to load doc"); 

      doc.LoadHtml("htmldoc.html"); // copied locally to bin folder, confirmed it found the file and loaded it 

      HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a"); // Always returns null, regardless of what I put in here 

      if (nodes != null) 
      { 
       foreach (HtmlNode item in nodes) 
       { 
        result += item.InnerText; 
       } 
      } 
      else 
      { 
       // Every. Single. Time. 
       throw new Exception("No matching nodes found in document"); 
      } 


      return result; 
     } 
     catch (Exception ex) 
     {     
      return ex.ToString(); 
     } 
    } 

源HTML文件 'htmldoc.html' 我使用的是這個樣子的:

<html> 
<head> 
    <title>Testing HTML Agility Pack</title> 
</head> 
<body> 
    <div id="div1"> 
     <a href="div1-a1">Link 1 inside div1</a> 
     <a href="div1-a2">Link 2 inside div1</a> 
    </div> 
     <a href="a3">Link 3 outside all divs</a>  
     <div id="div2"> 
     <a href="div2-a1">Link 1 inside div2</a> 
     <a href="div2-a2">Link 2 inside div2</a> 
    </div> 
</body> 
</html> 

回答

1

要加載你應該使用Load方法的文件.. LoadHtml是用於包含html的字符串

doc.Load("htmldoc.html"); 
+0

就這麼簡單。這解決了它。 –