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

c# html html-agility-pack parsing

我需要识别包含一些文本的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#做到这一点?

一般承认的答案

建立在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);
}

热门答案

尝试这个:

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现在包含所需divclass名。




许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因