代码之家  ›  专栏  ›  技术社区  ›  Vamsi

如何从C中的WebRequest类的响应中获取明文#

  •  1
  • Vamsi  · 技术社区  · 15 年前

    我想使用WebRequest类获得纯文本,就像我们使用 webbrowser1.Document.Body.InnerText . 我试过下面的代码

    public string request_Resource()
    {
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myurl);
       Stream stream = request.GetResponse().GetResponseStream();
       StreamReader sr = new StreamReader(stream);
       WebBrowser wb = new WebBrowser();
       wb.DocumentText = sr.ReadToEnd();
       return wb.Document.Body.InnerText;
    }
    

    当我执行的时候 NullReferenceException .

    有没有更好的方法得到一个纯文本。

    注意:我不能直接使用webbrowser控件加载网页,因为,我不想处理在加载网页时多次触发的所有事件。

    更新:根据建议,我已将代码更改为使用WebClient类而不是WebRequest 我的代码现在看起来像这样

    public string request_Resource()
    {
       WebClient wc = new WebClient();
       wc.Proxy = null;
       //The user agent header is added to avoid any possible errors
       wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0C)");
       return wc.DownloadString(myurl);
    }
    

    我正在考虑使用HTML实用程序包,谁能提出更好的选择。

    3 回复  |  直到 14 年前
        1
  •  3
  •   SLaks    15 年前

    你在找 HTML Agility Pack ,它可以在不使用IE的情况下解析HTML。
    它有一个 InnerText 财产。


    要回答您的问题,您需要等待浏览器解析文本。


    顺便说一下,你应该使用 WebClient 类而不是 WebRequest .

        2
  •  1
  •   Aliostad    15 年前

    使用网络客户端:

    public string request_Resource()
    {
        WebClient wc = new WebClient();
        byte[] data = wc.DownloadData(myuri);
        return Encoding.UTF8.GetString(data);
    }
    

    这将给你网站的内容。然后可以使用HtmlAgilityPack分析结果。

        3
  •  -2
  •   user179437    15 年前

    如果您只需要纯HTML文本,那么您已经编写了该代码。

    public string request_Resource()
    {
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myurl);
       Stream stream = request.GetResponse().GetResponseStream();
       StreamReader sr = new StreamReader(stream);
       return sr.ReadToEnd();
    }