使用C#通过div内的内容获取div类

时间:2016-05-17 09:08:55

标签: c# html parsing html-agility-pack

我需要识别包含一些文本的div元素的类。 例如,我有这个HTML页面

<html>
    ...
    <div class='x'>
        <p>this is the text I have.</p>
        <p>Another part of text.</p>
    </div>
    ...
</html>

所以我知道文本this is the text I have. Another part of text.我需要识别div类名。有没有办法用C#做到这一点?

2 个答案:

答案 0 :(得分:3)

试试这个:

string stringToSearch = "<p>this is the text I have.</p><p>Another part of text.</p>";
HtmlDocument document = new HtmlDocument();
document.LoadHtml(sb.ToString());

var classOfDiv = document.DocumentNode.Descendants("div").Select(x => new
{
    ClassOfDiv = x.Attributes["class"].Value
}).Where(x => x.InnerHtml = stringToSearch);

变量classOfDiv现在包含所需class的{​​{1}}名称。

答案 1 :(得分:3)

以diiN_的答案为基础。这有点冗长,但你应该能够从中得到你需要的东西。代码取决于HTML Agility Pack。你可以使用nuget来获得它。

var sb = new StringBuilder();
sb.AppendFormat("<html>");
sb.AppendFormat("<div class='x'>");
sb.AppendFormat("<p>this is the text I have.</p>");
sb.AppendFormat("<p>Another part of text.</p>");
sb.AppendFormat("</div>");
sb.AppendFormat("</html>");

const string stringToSearch = "<p>this is the text I have.</p><p>Another part of text.</p>";

var document = new HtmlDocument();
document.LoadHtml(sb.ToString());

var divsWithText = document
    .DocumentNode
    .Descendants("div")
    .Where(node => node.Descendants()
                       .Any(des => des.NodeType == HtmlNodeType.Text))
    .ToList();

var divsWithInnerHtmlMatching =
    divsWithText
        .Where(div => div.InnerHtml.Equals(stringToSearch))
        .ToList();

var innerHtmlAndClass =
    divsWithInnerHtmlMatching
        .Select(div => 
            new
            {
                InnerHtml = div.InnerHtml,
                Class = div.Attributes["class"].Value
            });

foreach (var item in innerHtmlAndClass)
{
Console.WriteLine("class='{0}' innerHtml='{1}'", item.Class, item.InnerHtml);
}