【问题标题】:extract formatted text and also href link from html using c#使用c#从html中提取格式化文本和href链接
【发布时间】:2022-02-10 02:02:51
【问题描述】:

我正在尝试提取文本以及 href 中的链接。

<html>
    <body>
        <p>foo <a href='http://www.example.com'>bar</a>
            <br> baz</p>
    </body>
</html>

我正在寻找输出,foo http://www.example.com bar baz 应该考虑 br 标签以获得正确的格式化句子。

【问题讨论】:

  • 您可以将HTMLAgilityPack 用于您的目的:html-agility-pack.net
  • 谢谢@RahulSharma。是否可以为此用例提供示例?提前致谢。
  • 我试过了,但我没有接受答案所需的声誉。我是堆栈溢出的新手。 @RahulSharma
  • 如果我的回答对您有所帮助,您可以通过单击答案旁边的复选框来接受它。 @Aishwarya Gujjar

标签: c# html html-to-text


【解决方案1】:

给你:

using System;
using HtmlAgilityPack;
                    
public class Program
{
    public static void Main()
    {
        var html =
        @"<html><body><p>foo <a href='http://www.example.com'>bar</a><br> baz</p></body></html> ";
        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);
        var htmlAnchor = htmlDoc.DocumentNode.SelectSingleNode("//a");
        var htmlBr = htmlDoc.DocumentNode.SelectSingleNode("//p");
        string hrefValue = htmlAnchor.Attributes["href"].Value;
        Console.WriteLine(htmlBr.InnerText + " " + hrefValue);
    }
}

输出:

富吧 baz http://www.example.com

工作示例:https://dotnetfiddle.net/BBYAF9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    相关资源
    最近更新 更多