【问题标题】:get div class by content inside div using C#使用 C# 通过 div 内的内容获取 div 类
【发布时间】:2016-05-17 17:49:45
【问题描述】:

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

【问题讨论】:

  • 是asp.net还是mvc?
  • 你关注的是 ASP.NET 还是 ASP.NET 和 MVC?
  • @Gaurav Singh Jantwal 这只是一个 html 代码。我有许多来自不同网站的页面(具有不同的 html 结构),我需要为每个页面识别文章文本的“html 边界”。完成后,我将使用 HTML AGILITY PACK 从每个页面获取 innerText。
  • 您可以将 HTML 页面读取为 XML 文档,然后使用 HTML 敏捷性您可以使用 selector 或迭代等进行检查。

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


【解决方案1】:

以 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);
}

【讨论】:

  • 如果无法向解决方案添加库怎么办?我们应该采用脏文本处理方式吗?
【解决方案2】:

试试这个:

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 名称。

【讨论】:

  • 谢谢。但是 x 没有 InterText 属性。怎么解决?
  • x 没有属性 InnerHtml 或 InnerText... 我将 HtmlAgilityPack 添加到项目中。所以这不是问题
  • 嘿,有足够的代表发表评论 - 问题是“.Select”。它正在创建一个新的匿名变量序列,每个变量都有一个“ClassOfDiv”属性,但 div 节点中包含的其余信息(选择中的“x”变量)被丢弃了。
  • @Donal 现在我明白了。谢谢
猜你喜欢
  • 2015-03-31
  • 2016-08-09
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
相关资源
最近更新 更多