【问题标题】:how to get only the parent tag text from html in C#如何在 C# 中仅从 html 中获取父标记文本
【发布时间】:2012-04-28 19:18:55
【问题描述】:

我实际上是在尝试从具有一些子标签的标签中获取文本

例如

<p><span>Child Text </span><span class="price">Child Text</span><br />
I need this text</p>

这就是我正在尝试的

HtmlElement menuElement = browser.Document.GetElementsByTagName("p");
String mytext = menuElement.InnerHtml;   //also tried innerText,OuterHtml,OuterText

更新:我认为我必须使用 Htmlagilitypack,所以现在我的问题是如何使用 htmlagilitypack 库来做到这一点,我是新手。

谢谢

【问题讨论】:

  • 由于需要在c#中查找,请从问题中删除javascript标签
  • @CharandeepSingh - 您可以对标签进行建议编辑,知道吗?
  • 基本上你需要作为文本节点的直接子节点。不确定HtmlElement 是否可行。 HTML Agility Pack 在这方面可能更加灵活。
  • 您应该能够遍历菜单元素中包含的元素并获取文本节点的内容,但我目前没有启动到 Windows,所以无法检查。
  • @Oded - 我不知道我有这种特权。谢谢;)

标签: c# html


【解决方案1】:

从使用正则表达式到网络抓取库有很多方法。我建议您使用 htmlagilitypack,您可以通过 xpath 准确解决您需要的内容。 向 HtmlAgilityPack 添加引用和命名空间,我正在使用 linq(这需要 .net 3.5 或更好的版本),下面的代码可以做到这一点。

using HtmlAgilityPack;
using System.Linq;

//这些引用必须可用。

        private void Form1_Load(object sender, EventArgs e)
        {
            var rawData = "<p><span>Child Text </span><span class=\"price\">Child Text</span><br />I need this text</p>";
            var html = new HtmlAgilityPack.HtmlDocument();
            html.LoadHtml(rawData);
            html.DocumentNode.SelectNodes("//p/text()").ToList().ForEach(x=>MessageBox.Show(x.InnerHtml));
        }

【讨论】:

    【解决方案2】:

    如果您可以将“需要此文本”放在带有 id 的 span 中,那就容易多了——然后您只需获取该 id 的 .innerHTML()。如果无法更改标记,则可以获取 menuElement 的 .innerHTML() 和字符串匹配“
    ”之后的内容,但这很脆弱。

    【讨论】:

    • 感谢 robrich,但我无法更改 html 代码,此外,我还有很多标签要通过循环获取,因此匹配字符串不是我的选择。
    【解决方案3】:

    您可以通过将 DocumentText 拆分为不同的部分来获取文本。

    string text = "<p><span>Child Text </span><span class="price">Child Text</span><br />I need this text</p>";
    text = text.Split(new string{"<p><span>Child Text </span><span class="price">Child Text</span><br />"}, StringSplitOptions.None)[1];
    // Splits the first part of the text, leaving us with "I need this text</p>"
    // We can remove the last </p> many ways, but here I will show you one way.
    text = text.Split(new string{"</p>"}, StringSplitOptions.None)[0];
    // text now has the value of "I need this text"
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 2021-09-28
      • 1970-01-01
      相关资源
      最近更新 更多