private void btnASPNET_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> postParams = new Dictionary<string, string>();
            postParams.Add("txtLoginId", "www.cnuunet.com");
            postParams.Add("txtPassword", "www.cnuunet.com");
            postParams.Add("btnLogin", "Sign in");
            textBox1.Text = GetAspNetCodeResponseDataFromWebSite(postParams, "http://www.cnuunet.com/login.aspx", "http://www.cnuunet.com/ProductList.aspx");
        }

/// <summary>
        /// ASP.net页面登录方式 通过post密码方式读取网页内容
        /// 在本页面(login.aspx)的.cs文件内验证用户名和密码。
        /// Asp.net验证需要记住本次页面加载的__VIEWSTATE和__EVENTVALIDATION信息,并且需要button按钮的ID和Text信息
        /// </summary>
        /// <param name="postParams">用户名(用户名文本框的ID和内容)、密码(密码文本框的ID和内容)、summit按钮(button按钮的ID和Text)</param>
        /// <param name="getViewStateAndEventValidationLoginUrl">需要验证登陆信息的url</param>
        /// <param name="getDataUrl">需要抓取数据的网页url</param>
        /// <returns>抓取页面返回的html信息</returns>
        private string GetAspNetCodeResponseDataFromWebSite(Dictionary<string, string> postParams, string getViewStateAndEventValidationLoginUrl, string getDataUrl)
        {
            if (postParams == null || postParams.Keys.Count!=3)
            {
                string errorMessage = "参数中需要包含如下3个信息,缺一不可。用户名(用户名文本框的ID和内容)、密码(密码文本框的ID和内容)、summit按钮(button按钮的ID和Text)";
                MessageBox.Show(errorMessage);
                return errorMessage ;
            }

try
            {
                CookieContainer cookieContainer = new CookieContainer();

///////////////////////////////////////////////////
                // 1.打开 MyLogin.aspx 页面,获得 GetVeiwState & EventValidation
                ///////////////////////////////////////////////////                
                // 设置打开页面的参数
                HttpWebRequest request = WebRequest.Create(getViewStateAndEventValidationLoginUrl) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;

// 接收返回的页面
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string srcString = reader.ReadToEnd();

// 获取页面的 VeiwState,分析返回的页面,解析出__VIEWSTATE的值          
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

// 获取页面的 EventValidation,分析返回的页面,解析出__VIEWSTATE的值                   
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

///////////////////////////////////////////////////
                // 2.自动填充并提交 Login.aspx 页面,提交Login.aspx页面,来保存Cookie
                ///////////////////////////////////////////////////

// 将文本转换成 URL 编码字符串
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
                
                // 要提交的字符串数据。格式形如:user=uesr1&password=123
                string postString = "";
                foreach (KeyValuePair<string, string> de in postParams)
                {
                    //把提交按钮中的中文字符转换成url格式,以防中文或空格等信息
                    postString += System.Web.HttpUtility.UrlEncode(de.Key.ToString()) + "=" + System.Web.HttpUtility.UrlEncode(de.Value.ToString()) + "&";
                }
                postString += string.Format("__VIEWSTATE={0}&__EVENTVALIDATION={1}", viewState, eventValidation);
                
                // 将提交的字符串数据转换成字节数组
                byte[] postData = Encoding.ASCII.GetBytes(postString);

// 设置提交的相关参数
                request = WebRequest.Create(getViewStateAndEventValidationLoginUrl) as HttpWebRequest;
                request.Method = "POST";
                request.KeepAlive = false;
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookieContainer;
                request.ContentLength = postData.Length;

// 提交请求数据
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

// 接收返回的页面
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("GB2312"));
                srcString = reader.ReadToEnd();

///////////////////////////////////////////////////
                // 3.打开需要抓取数据的页面
                ///////////////////////////////////////////////////
                // 设置打开页面的参数
                request = WebRequest.Create(getDataUrl) as HttpWebRequest;
                request.Method = "GET";
                request.KeepAlive = false;
                request.CookieContainer = cookieContainer;

// 接收返回的页面
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                srcString = reader.ReadToEnd();
                return srcString;
                ///////////////////////////////////////////////////
                // 4.分析返回的页面
                ///////////////////////////////////////////////////
                // ...... ......
            }
            catch (WebException we)
            {
                string msg = we.Message;
                return msg;
            }  
        }

C# asp.net 抓取需要登录的网页内容 抓取asp.net登录验证的网站的更多相关文章

  1. Scrapy 通过登录的方式爬取豆瓣影评数据

    Scrapy 通过登录的方式爬取豆瓣影评数据 爬虫 Scrapy 豆瓣 Fly 由于需要爬取影评数据在来做分析,就选择了豆瓣影评来抓取数据,工具使用的是Scrapy工具来实现.scrapy工具使用起来 ...

  2. Linux--多用户登录服务器端口抓包

    以root身份登录1.新建用户组用命令groupadd test2.添加用户useradd -d /home/test/bei_1 -s /bin/sh -g test -m bei_1此命令新建了一 ...

  3. Python登录豆瓣并爬取影评

    上一篇我们讲过Cookie相关的知识,了解到Cookie是为了交互式web而诞生的,它主要用于以下三个方面: 会话状态管理(如用户登录状态.购物车.游戏分数或其它需要记录的信息) 个性化设置(如用户自 ...

  4. 《吐血整理》高级系列教程-吃透Fiddler抓包教程(34)-Fiddler如何抓取微信小程序的包-上篇

    1.简介 有些小伙伴或者是童鞋们说小程序抓不到包,该怎么办了???其实苹果手机如果按照宏哥前边的抓取APP包的设置方式设置好了,应该可以轻松就抓到包了.那么安卓手机小程序就比较困难,不是那么友好了.所 ...

  5. Asp.Net Core 项目实战之权限管理系统(5) 用户登录

    0 Asp.Net Core 项目实战之权限管理系统(0) 无中生有 1 Asp.Net Core 项目实战之权限管理系统(1) 使用AdminLTE搭建前端 2 Asp.Net Core 项目实战之 ...

  6. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(15)-用户登录详细错误和权限数据库模型设计

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(15)-用户登录详细错误和权限数据库模型设计     ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)    ...

  7. Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  8. Fiddler抓包学习——https请求的抓取

    第一步:设置Fiddler  windows下安装证书 打开fiddler 查看证书是否安装 说明已安装成功 设置端口号(下面手机设置代理所需要的) 第二部  手机端安装证书 通过fiddler查看电 ...

  9. 第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解

    第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解 封装模块 #!/usr/bin/env python # -*- coding: utf- ...

随机推荐

  1. springSecurity自定义认证配置

    上一篇讲了springSecurity的简单入门的小demo,认证用户是在xml中写死的.今天来说一下自定义认证,读取数据库来实现认证.当然,也是非常简单的,因为仅仅是读取数据库,权限是写死的,因为相 ...

  2. Spring RedisTemplate操作-哈希操作(3)

    @Autowired @Resource(name="redisTemplate") private RedisTemplate<String, String> rt; ...

  3. H5 以及 CSS3

    <!DOCTYPE html> <html> <head> <style> *{ padding:0; margin:0; } header{ disp ...

  4. go语言学习之路(一)Hello World

    为什么要使用 Go 语言?Go 语言的优势在哪里? 1.部署简单. 2.并发性好. 3.良好的语言设计. 4.执行性能好. Go环境搭建 Golang下载 国外镜像  https://www.gola ...

  5. ASP.NET私有构造函数作用

    一.私有构造函数的特性 1.一般构造函数不是私有或者保护成员,但构造函数可以使私有成员函数,在一些特殊的场合,会把构造函数定义为私有或者保护成员. 2.私有构造函数是一种特殊的实例构造函数.它通常用在 ...

  6. PHP-Redis操作

    /*1.Connection*/ $redis = new Redis(); $redis->connect('127.0.0.1',6379,1);//短链接,本地host,端口为6379,超 ...

  7. MySQL用户密码过期登陆报错ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

    今天接到主从复制失败告警,查看MySQL,发现MySQL能够登陆但是执行命令报错, ERROR 1820 (HY000): You must reset your password using ALT ...

  8. python3操作sqlserver,查询数据统计导出csv

    import pymssql #导入sqlserver连接池模块 import csv #导出csv文件使用模块 conn=pymssql.connect('服务器ip','用户名','密码','数据 ...

  9. Android Service总结06 之AIDL

    Android Service总结06 之AIDL 版本 版本说明 发布时间 发布人 V1.0 初始版本 2013-04-03 Skywang           1 AIDL介绍 AIDL,即And ...

  10. NFS基础配置

    需要安装的包: rpc-bind nfs-utils 修改配置文件 /etc/exports 配置 /tmp *(ro) 修改配置之后记得重启服务 sudo systemctl restart nfs ...