2012-02-05 67 views
6

我試圖HtmlAgilityPack和下面的代碼,但它不會從HTML列表捕獲文本:如何從HTML源文件中提取頁面上可見的文本?

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(htmlStr); 
HtmlNode node = doc.DocumentNode; 
return node.InnerText; 

這裏是一個失敗的代碼:

<as html> 
<p>This line is picked up <b>correctly</b>. List items hasn't...</p> 
<p><ul> 
<li>List Item 1</li> 
<li>List Item 2</li> 
<li>List Item 3</li> 
<li>List Item 4</li> 
</ul></p> 
</as html> 
+0

這可能是因爲Javascript。 – SLaks 2012-02-05 23:00:01

+0

顯示您正在分析的HTML。 – RedFilter 2012-02-05 23:03:51

+0

@RedFilter我已經更新了HTML。 – 2012-02-05 23:13:51

回答

2

InnerText下面這段代碼工作對我來說:

string StripHTML(string htmlStr) 
{ 
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
    doc.LoadHtml(htmlStr); 
    var root = doc.DocumentNode; 
    string s = ""; 
    foreach (var node in root.DescendantNodesAndSelf()) 
    { 
     if (!node.HasChildNodes) 
     { 
      string text = node.InnerText; 
      if (!string.IsNullOrEmpty(text)) 
      s += text.Trim() + " ";      
     } 
    } 
    return s.Trim(); 
} 
3

因爲你需要走到樹和CONCAT在某種程度上所有節點

相關問題