华域联盟 .Net ASP.NET抓取网页内容的实现方法

ASP.NET抓取网页内容的实现方法

本文实例讲述了ASP.NET抓取网页内容的实现方法。分享给大家供大家参考。具体实现方法如下:

一、ASP.NET 使用HttpWebRequest抓取网页内容

复制代码 代码如下:
/// <summary>方法一:比较推荐 

/// 用HttpWebRequest取得网页源码 

/// 对于带BOM的网页很有效,不管是什么编码都能正确识别 

/// </summary> 

/// <param name="url">网页地址" </param> 

/// <returns>返回网页源文件</returns> 

public static string GetHtmlSource2(string url) 



    //处理内容 

    string html = ""; 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

    request.Accept = "*/*"; //接受任意文件 

    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"; //  

    request.AllowAutoRedirect = true;//是否允许302 

    //request.CookieContainer = new CookieContainer();//cookie容器, 

    request.Referer = url; //当前页面的引用 

    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

    Stream stream = response.GetResponseStream(); 

    StreamReader reader = new StreamReader(stream, Encoding.Default); 

    html = reader.ReadToEnd(); 

    stream.Close(); 

    return html; 

}

二、ASP.NET 使用 WebResponse 抓取网页内容

复制代码 代码如下:
public static string GetHttpData2(string Url) 



    string sException = null; 

    string sRslt = null; 

    WebResponse oWebRps = null; 

    WebRequest oWebRqst = WebRequest.Create(Url); 

    oWebRqst.Timeout = 50000; 

    try 

    { 

        oWebRps = oWebRqst.GetResponse(); 

    } 

    catch (WebException e) 

    { 

        sException = e.Message.ToString(); 

    } 

    catch (Exception e) 

    { 

        sException = e.ToString(); 

    } 

    finally 

    { 

        if (oWebRps != null) 

        { 

            StreamReader oStreamRd = new StreamReader(oWebRps.GetResponseStream(), Encoding.GetEncoding("utf-8")); 

            sRslt = oStreamRd.ReadToEnd(); 

            oStreamRd.Close(); 

            oWebRps.Close(); 

        } 

    } 

    return sRslt; 

}

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:

  • asp.net中获取远程网页的内容之一(downmoon原创)
  • asp.net下获取远程网页的内容之二(downmoon原创)
  • asp.net 网页编码自动识别代码
  • asp.net HttpWebRequest自动识别网页编码
  • asp.net(c#)做一个网页数据采集工具
  • HttpWebRequest和HttpWebResponse用法小结
  • ASP.NET MVC中解析淘宝网页出现乱码问题的解决方法
  • asp.net 抓取网页源码三种实现方法
  • C#中HttpWebRequest的用法详解
  • ASP.NET使用HttpWebRequest读取远程网页源代码

本文由 华域联盟 原创撰写:华域联盟 » ASP.NET抓取网页内容的实现方法

转载请保留出处和原文链接:https://www.cnhackhy.com/56286.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部