我使用以下代碼將頁面中的所有文本轉換為List<string>
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);
foreach (var script in doc.DocumentNode.Descendants("script").ToArray())
script.Remove();
foreach (var style in doc.DocumentNode.Descendants("style").ToArray())
style.Remove();
foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//text()"))
{
string found = WebUtility.HtmlDecode(node.InnerText.Trim());
if (found.Length > 2) // removes some unwanted strings
query[item.Key].Add(found);
}
</form>
是否有更好的方法來縮小這段代碼,所以我只得到每個標籤的文本而沒有別的或者我將不得不解析結果以刪除<*>標籤? 僅使用HAP中包含的功能就可以輕鬆完成此操作。
HtmlDocument doc = new HtmlWeb().Load("http://www.google.com");
List<string> words = doc.DocumentNode.DescendantNodes()
.Where(n => n.NodeType == HtmlNodeType.Text
&& !string.IsNullOrWhiteSpace(HtmlEntity.DeEntitize(n.InnerText))
&& n.ParentNode.Name != "style" && n.ParentNode.Name != "script")
.Select(n => HtmlEntity.DeEntitize(n.InnerText).Trim())
.Where(s => s.Length > 2).ToList();
結果是一個長度超過2的單詞列表,所有內容都已經轉義,因此不需要WebUtility
。