C# 如何使用HTML Agility Pack从特定类中提取文本?

C# 如何使用HTML Agility Pack从特定类中提取文本?,c#,html-agility-pack,C#,Html Agility Pack,例如,我想从中提取第一个定义。不过,这是原始文本 var html = new HtmlDocument(); html.LoadHtml(new WebClient().DownloadString("http://www.urbandictionary.com/define.php?term=potato")); var root = html.DocumentNode;

例如,我想从中提取第一个定义。不过,这是原始文本

                    var html = new HtmlDocument();
                html.LoadHtml(new WebClient().DownloadString("http://www.urbandictionary.com/define.php?term=potato"));
                var root = html.DocumentNode;
                var p = root.Descendants()
                    .Where(n => n.GetAttributeValue("class", "").Equals("meaning"))
                    .Single()
                    .Descendants("")
                    .Single();
                var content = p.InnerText;

这是我用来尝试提取类含义的代码。这根本不起作用,不过。。。如何从Urban Dictionary中提取该类?

如果您按以下方式更改代码,它将正常工作

var html = new HtmlDocument();
html.LoadHtml(new WebClient().DownloadString("http://www.urbandictionary.com/define.php?term=potato"));
var root = html.DocumentNode;
var p = root.SelectNodes("//div[@class='meaning']").First();
var content = p.InnerText;

我在
SelectNodes
中使用的文本是并表示所有
div
元素,其类名为
表示
。您需要使用
First
FirstOrDefault
,因为页面包含多个具有该类名的
div
元素,因此
Single
将引发异常。

如果您想使用与所使用链接相同的“样式”,您也可以使用

var p = root.Descendants()
    .Where(n => n.GetAttributeValue("class", "").Equals("meaning"))
    .FirstOrDefault();

虽然Tone的答案更优雅,但一行程序通常更好。

您应该调试您的查询并找出错误所在-一次一级LINQ查询。如果你不能找出具体的情况,请确保提供(包括文章中的最小内联数据)。