我正在使用以下代码将页面中的所有文本放入 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);
}
- 但一些 html 仍在进入字符串,例如
</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
。
关于c# - 迭代所有元素并获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10808099/