您好,登录后才能下订单哦!
本篇文章给大家分享的是有关如何在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;  
}
以上就是如何在ASP.NET项目中抓取网页内容,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。