使用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合法嗎? 是的,了解原因