【问题标题】:how to convert html to plain text c#?如何将html转换为纯文本c#?
【发布时间】:2016-10-13 07:24:56
【问题描述】:

我正在尝试从 html 网站获取纯文本,但我得到的是 html 代码而不是纯文本。例如 hello

它的我

如何将其转换为 hello是我 。很感谢任何形式的帮助!这是我的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
 using System.Net;
 using System.Text.RegularExpressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

 namespace WindowsFormsApplication2
 {
   public partial class Form1 : Form
   {
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(""https://www.dailyfx.com/real-time-news");
        myRequest.Method = "GET";
        WebResponse myResponse = myRequest.GetResponse();
        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        string result = sr.ReadToEnd();




        textBox1.Text = result;
        sr.Close();
        myResponse.Close();
    }
    }
}

【问题讨论】:

标签: c# html


【解决方案1】:
 You can use regex expressions for this. 

 Regex.Replace(htmltext, "<.*?>", string.Empty);

 Eg:- String htmltext = "string html = "<p>Test1 <b>.NET</b> Test2 Test3 
                         <i>HTML</i> Test4.</p>";"
      Output will be :- Test1 Test2 Test3 Test4.

这将对您有所帮助。 http://www.codeproject.com/Tips/136704/Remove-all-the-HTML-tags-and-display-a-plain-text

【讨论】:

    【解决方案2】:

    简答:没有直接转化;您正在“抓取”网站;解析结果字符串以提取您需要的内容(或者更好的是,查看相关网站是否提供了 API)。

    网站以 HTML 而非纯文本呈现。尽管您将结果作为字符串返回,但您需要对其进行解析以提取您感兴趣的文本。实际提取高度取决于您要完成的任务。如果网站是正确的 XHTML,您可以将其加载到 XDocument 作为 XML 并遍历树以获取您需要的信息;否则,其中一个 cmets 中建议的 HTMLAgilityPack 可能会有所帮助(不像评论所暗示的那样神奇 - 它比 GetString 工作要多一点...)

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2011-01-25
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 2014-09-08
      • 2013-10-14
      相关资源
      最近更新 更多