使用C#通过div中的内容获取div类 [英] get div class by content inside div using C#

查看:161
本文介绍了使用C#通过div中的内容获取div类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定包含一些文本的 div 元素的类.例如,我有这个HTML页面

I need to identify the class of a div element which contains some text. For example I have this HTML page

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

所以我知道文本这是我的文本.文本的另一部分.而且我需要确定div类的名称.有没有办法使用C#做到这一点?

So I know the text this is the text I have. Another part of text. And I need to identify the div class name. Is there an way to do this using C#?

推荐答案

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

Building on the answer of diiN_. This is a bit verbose but you should be able to get what you need from it. The code depends on the HTML Agility Pack. You can get it using 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);
}

这篇关于使用C#通过div中的内容获取div类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆