asp.net 抓取网页源码三种实现方法

方法1 比较推荐

/// <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)"; // 模拟使用IE在浏览 http://www.52mvc.com
      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;
    }

方法2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Net;

namespace MySql
{
  public class GetHttpData
  {
    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;
    }

  }
}

方法3

public static string getHtml(string url, params string [] charSets)//url是要访问的网站地址,charSet是目标网页的编码,如果传入的是null或者"",那就自动分析网页的编码
  {
    try
    {
      string charSet = null;
      if (charSets.Length == 1) {
        charSet = charSets[0];
      }
      WebClient myWebClient = new WebClient(); //创建WebClient实例myWebClient
      // 需要注意的:
      //有的网页可能下不下来,有种种原因比如需要cookie,编码问题等等
      //这是就要具体问题具体分析比如在头部加入cookie
      // webclient.Headers.Add("Cookie", cookie);
      //这样可能需要一些重载方法。根据需要写就可以了

      //获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
      myWebClient.Credentials = CredentialCache.DefaultCredentials;
      //如果服务器要验证用户名,密码
      //NetworkCredential mycred = new NetworkCredential(struser, strpassword);
      //myWebClient.Credentials = mycred;
      //从资源下载数据并返回字节数组。(加@是因为网址中间有"/"符号)
      byte[] myDataBuffer = myWebClient.DownloadData(url);
      string strWebData = Encoding.Default.GetString(myDataBuffer);

      //获取网页字符编码描述信息
      Match charSetMatch = Regex.Match(strWebData, "<meta([^<]*)charset=([^<]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
      string webCharSet = charSetMatch.Groups[2].Value;
      if (charSet == null || charSet == "")
        charSet = webCharSet;

      if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
      {
        strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
      }
      else {
        strWebData = Encoding.GetEncoding("utf-8").GetString(myDataBuffer);
      }
      return strWebData;
    }
    catch (Exception e) { return ""; }
  }

asp.net 获取网页源文件的方法

有时候我们需要获取 网页源文件,所以用以下这个方法很容易完成任务!

private string GetStringByUrl(string strUrl)
{
  WebRequest wrt = WebRequest.Create(strUrl);
  WebResponse wrse = wrt.GetResponse();
  Stream strM = wrse.GetResponseStream();
  StreamReader SR = new StreamReader(strM,  Encoding.GetEncoding("gb2312"));
  string strallstrm = SR.ReadToEnd();
  return strallstrm;
} 

只要传入要下载网页的地址就OK了!
通过这个方法做个源码导出:

private string SaveHTML()
 {
string str = RenderPage("Default2.aspx");
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
    Response.AddHeader("Content-Disposition","attachment;filename=index.html"); //解决中文文件名乱码
    Response.AddHeader("Content-length",str.Length.ToString());
    Response.Write(str);
    Response.End();
} 

以上就是asp.net 抓取网页源码的全部代码了,希望对大家有所帮助。

(0)

相关推荐

  • ASP.NET使用HttpWebRequest读取远程网页源代码

    读取远程网页能做什么就不用多说了吧,做小偷程序或是采集,也就诸如此类了吧. public string GetPage(string url) { HttpWebRequest request = null; HttpWebResponse response = null; StreamReader reader = null; try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 20000; req

  • asp.net HttpWebRequest自动识别网页编码

    复制代码 代码如下: static string GetEncoding(string url) { HttpWebRequest request = null; HttpWebResponse response = null; StreamReader reader = null; try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 20000; request.AllowAutoRedirect

  • asp.net下获取远程网页的内容之二(downmoon原创)

    本文仅针AD下代理上网的情况: 代码如下: 1.定义变量:  定义变量#region  定义变量 复制代码 代码如下: private    string strFireWallIP          ...{              get              ...{                  return System.Configuration.ConfigurationSettings.AppSettings["strFireWallIP"];        

  • ASP.NET MVC中解析淘宝网页出现乱码问题的解决方法

    最近在解析淘宝中商品的信息,结果出现乱码,如: 原因就是中文字符格式出现冲突,ASP.NET MVC 默认采用utf-8,但是淘宝网页采用gbk. 在网上找了一下,最常用的解决方法就是修改web.config: < system.web> ...... < globalization requestEncoding="gbk" responseEncoding="gbk" culture="zh-CN" fileEncoding

  • asp.net 网页编码自动识别代码

    复制代码 代码如下: using System; using System.Net; using System.Text; using System.Text.RegularExpressions; class Program { // 获取网页的HTML内容,根据网页的charset自动判断Encoding static string GetHtml(string url) { return GetHtml(url, null); } // 获取网页的HTML内容,指定Encoding sta

  • HttpWebRequest和HttpWebResponse用法小结

    最近公司拓展市场异常迅猛,数周之类开出去几十套系统,虽然系统名字不一样,但各个内容相似.由于时间紧迫,很多开出去的系统 出现各种神奇的错误,当初虽然有记录错误日志,然而很多客户使用的是自己的服务器和数据库,出了问题我们并不能立即掌握信息, 因此决定做一个捕获所有系统的异常并保存到自家数据库中. 实现思路 在每个系统出写入报告错误代码(找个合理的理由,比如系统免费升级) -> 自家服务器接收并处理错误报告 -> 反馈用户(解决掉BUG就行,不要太声扬) 基础回顾 ---参考msdn 1.Http

  • asp.net中获取远程网页的内容之一(downmoon原创)

    获取远程网页的内容之一(downmoon原创) 一.本机直接上网时: 获取指定远程网页内容#region 获取指定远程网页内容 复制代码 代码如下: /**//// <summary>          /// 获取指定远程网页内容          /// </summary>          /// <param name="strUrl">所要查找的远程网页地址</param>          /// <param nam

  • asp.net(c#)做一个网页数据采集工具

    通过这个软件一两天就完成了几千产品数据的录入,可见很多工作不是一味用人工去做,作为一个程序员,就是要让很多让那些经常做重复性的.繁琐的工作中的人解放出来.下面只是写了一些核心代码,而且采集必须要和对应网站相挂钩,作者:郑少群 复制代码 代码如下: //提取产品列表页中产品最终页的网页 private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Trim() == "" || textBox2.Te

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

    本文实例讲述了ASP.NET抓取网页内容的实现方法.分享给大家供大家参考.具体实现方法如下: 一.ASP.NET 使用HttpWebRequest抓取网页内容 复制代码 代码如下: /// <summary>方法一:比较推荐  /// 用HttpWebRequest取得网页源码  /// 对于带BOM的网页很有效,不管是什么编码都能正确识别  /// </summary>  /// <param name="url">网页地址" </

  • C#中HttpWebRequest的用法详解

    本文实例讲述了C#中HttpWebRequest的用法.分享给大家供大家参考.具体如下: HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交.下面对这两种方式进行一下说明: GET 方式: GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.jb51.net/?hl=zh-CN 中,前面部分 http://www.jb51.net表示数据提交的网址,后面部分 hl=zh-CN 表示附

随机推荐