栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

一、ASP.NET 使用HttpWebRequest抓取网页内容
复制代码 代码如下:///

方法一:比较推荐 
/// 用HttpWebRequest取得网页源码 
/// 对于带BOM的网页很有效,不管是什么编码都能正确识别 
///
 
/// 网页地址"  
/// 返回网页源文件 
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#程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/56874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号