【问题标题】:Convert webpage into plain text..?将网页转换为纯文本..?
【发布时间】:2011-10-01 08:51:44
【问题描述】:

我正在尝试将网页转换为纯文本。但是,如果我遇到表格,我也会得到 td 和 tr 标签。如果我替换那些表格标签,那么我将无法获取某些内容。

这是我的代码

string s = Regex.Replace(htmldoc, "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
s = Regex.Replace(s, "<!--.*?-->", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
s = Regex.Replace(s, "<style.*?style>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
s = Regex.Replace(s, "<a.*?a>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
s = Regex.Replace(s, "<img.*?img>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
s = Regex.Replace(s, "<table.*?table>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(s);
s = doc.DocumentNode.SelectSingleNode("//body").InnerText.Trim();

请检查一下并告诉我如何在不获取 td 和 tr 标签的情况下从表中获取内容。

【问题讨论】:

标签: c# regex html-agility-pack


【解决方案1】:

如果您使用 HTML Agility 包来解析表格,则无需使用正则表达式删除 HTML 标记。 SO上有一些使用HTML Agility包解析表格的好例子。例如:HTML Agility pack - parsing tables

【讨论】:

    【解决方案2】:

    可以使用正文的InnerText

    string html = @"
    <html>
        <title>title</title>
        <body>
               <h1> The wheel.</h1>
               Stop reinventing the wheel ! Use powerful APIs 
               for manipulating html docs !
               <h3> I am fine </h3>
               <img src=""da_wheel_in_my_mind.png""/>
        </body>
    </html>";
    
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);
    string text = doc.DocumentNode.SelectSingleNode("//body").InnerText;
    

    接下来,您可能想要折叠空格和换行:

    text = Regex.Replace(text, @"\s+", " ").Trim();
    

    但是请注意,虽然它在这种情况下工作,但 hello&lt;br&gt;worldhello&lt;i&gt;world&lt;/i&gt; 等标记将由 InnerText 转换为 helloworld - 删除标签。这个问题很难解决,因为显示通常由 CSS 决定,而不仅仅是由标记决定。

    【讨论】:

    • 我已经这样做了..但我的问题是如何解析表...?如果一个表包含另一个表,而您不知道它包含多少表,那么您将如何获取内部文本
    • 有些东西我不明白。你如何加载你的htmldoc 变量?
    • Webclient wb=new WebClient();htmldoc=wb.downloadstring(querry);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-09-08
    • 2020-08-27
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多