模拟web访问有登录且有验证码的登录后抓取数据

1 取验证码

1 在窗体上放一个picturebox (imgValidate)存放获取的验证码图片,
2 用浏览器的开发者工具firefox (f12) 分析出验证码的网址
private void GetValidateImage()
        {
            cookies = new CookieContainer();
            string strUrl = "http://www.xxx.com/ValidateCodePicture.aspx?Key="+strValidCode;  //验证码页面 strValidCode这个随机码要先取出来

CookieContainer cc = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);

//set request args
            request.Method = "Get";
            request.CookieContainer = cc;
            request.KeepAlive = true;

//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.ContentType = "text/html";

//模拟goole浏览器访问
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
            //request.Referer = strUrl;
            request.Headers.Add("x-requested-with:XMLHttpRequest");
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en;q=0.6,nl;q=0.4,zh-TW;q=0.2");
            //request.ContentLength = postdataByte.Length;  text/html; charset=utf-8
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip |
                                             DecompressionMethods.None;
            //支持跳转页面,查询结果将是跳转后的页面
            request.AllowAutoRedirect = true;

request.Headers.Add("Accept-Encoding", "gzip, deflate");
            if (request.Method == "POST")
            {
                (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";
            }

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

MemoryStream ms = null;
            using (var stream = response.GetResponseStream())
            {
                Byte[] buffer = new Byte[response.ContentLength];
                int offset = 0, actuallyRead = 0;
                do
                {
                    actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
                    offset += actuallyRead;
                }
                while (actuallyRead > 0);
                ms = new MemoryStream(buffer);
            }
            response.Close();

cookies = request.CookieContainer; //保存cookies
            strCookies = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies转换成字符串

Bitmap sourcebm = new Bitmap((Stream)ms);//初始化Bitmap图片
            imgValidate.Image = sourcebm;
        }

2 取js赋值的内容

有的网页用查看网页源代码的方式看不到控件的值,需要用到下面的方法
  即用C#自带的webbrowse来加载网页,再用webBrowser1.Document来取对应控件的值,如
  tring strMsg2 = webBrowser1.Document.GetElementById("hdValidateCodeID").OuterHtml;

3 取得要提交的参数

如果是asp.net的网页还有提交”__EVENTTARGET“,"__EVENTARGUMENT","__VIEWSTATE"这三个参数,这个也可以在开发者工具-网络-参数里看到
可以用httpRequest先取得源代码再分析出
这里用的是webbrowse里加载好的
  
        private void GetViewState()
        {
            string strMsg = webBrowser1.Document.GetElementById("__VIEWSTATE").OuterHtml;
            //取viewstate value
            //<INPUT id=__VIEWSTATE type=hidden value=/wEPDwUKMTg0NTk3Mjg2N2Rk name=__VIEWSTATE>
            MatchCollection mc = Regex.Matches(strMsg, "id=__VIEWSTATE.*(?<viewstate>value[^>]*)", RegexOptions.IgnoreCase);

if (mc.Count > 0)
            {
                foreach (Match m in mc)
                {
                    strViewState = m.Groups["viewstate"].Value.ToString().Trim();
                    if (strViewState.Length > 0)
                    {
                        strViewState = strViewState.Replace("value=", "").Replace("\"", "").Replace("\\", "").Replace("name=__VIEWSTATE","").Replace(" ","");
                    }
                }
            }

//<INPUT id=hdValidateCodeID type=hidden value=c1b52d3a-1f8b-1dc4-0d44-32a4b46ef8af name=hdValidateCodeID>
            string strMsg2 = webBrowser1.Document.GetElementById("hdValidateCodeID").OuterHtml;
            MatchCollection mc2 = Regex.Matches(strMsg2, "id=hdValidateCodeID.*(?<validatecode>value[^>]*)", RegexOptions.IgnoreCase);

if (mc2.Count > 0)
            {
                foreach (Match m in mc2)
                {
                    strValidCode = m.Groups["validatecode"].Value.ToString().Trim();
                    if (strValidCode.Length > 0)
                    {
                        strValidCode = strValidCode.Replace("value=", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("name=hdValidateCodeID","").Replace(" ","");
                    }
                }
            }
            txtValidCode.Text = strValidCode;
            txtViewState.Text = strViewState;

//String 的Cookie 要转成 Cookie型的 并放入CookieContainer中  
            string cookieStr = webBrowser1.Document.Cookie;
            string[] cookstr = cookieStr.Split(';');

foreach (string str in cookstr)
            {
                try
                {
                    string[] cookieNameValue = str.Split('=');
                    Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    ck.Domain = "XXX.com"; //必须写对  
                    myCookieContainer.Add(ck);
                }
                catch
                {
                }
            }  
        }

4 登录并且存取cookie

提交参数,并存下cookie,供后续用
private void Login()
        {
            cookies = new CookieContainer();
            string strUrl = "http://www.xxx.com/Login.aspx";  //验证码页面

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

//set request args
            request.Method = "POST";
            request.CookieContainer = myCookieContainer;
            request.KeepAlive = true;

//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.ContentType = "text/html";

//模拟goole浏览器访问
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
            //request.Referer = strUrl;
            request.Headers.Add("x-requested-with:XMLHttpRequest");
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en;q=0.6,nl;q=0.4,zh-TW;q=0.2");
            //request.ContentLength = postdataByte.Length;  text/html; charset=utf-8
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip |
                                             DecompressionMethods.None;
            //支持跳转页面,查询结果将是跳转后的页面
            request.AllowAutoRedirect = true;

request.Headers.Add("Accept-Encoding", "gzip, deflate");
            if (request.Method == "POST")
            {
                (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";
            }

//---begin
           
            string postData = string.Format("txtUserName={0}&txtPassword={1}&txtValidateCode={2}&hdValidateCodeID={3}&ddlLanguage=CN&btnLogin=登录&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={4}", txtUserName.Text, txtPassword.Text, txtValidate.Text,strValidCode,strViewState);  //这里按照前面FireBug中查到的POST字符串做相应修改。
            byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
           
            request.ContentLength = postdatabyte.Length;

using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postdatabyte, 0, postdatabyte.Length);
            }
            //---end---

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

//StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string strMsg = reader.ReadToEnd();

response.Close();

cookies = request.CookieContainer; //保存cookies,后面再请求其它网页就可用这个cookie,不用在登录了
            lbLogin.Text = "已登录";
            btnSearchResume.Enabled = true;

}

模拟web访问有登录且有验证码的登录后抓取数据相关推荐

  1. python登录网页后抓取数据_Python抓取网页数据的终极办法

    Pandas库有一种内置的方法,可以从名为read_html()的html页面中提取表格数据: https://pandas.pydata.org/import pandas as pdtables ...

  2. python3爬虫系列23之selenium+腾讯OCR识别验证码登录微博且抓取数据

    python3爬虫系列23之selenium+腾讯OCR识别验证码登录微博且抓取数据 1.前言 上一篇是一个 python3爬虫系列22之selenium模拟登录需要验证码的微博且抓取数据, 我们是首 ...

  3. python–爬虫–模拟登录全面介绍和简例–以抓取雅卓app为例

    转载请注明出处:python–爬虫–模拟登录全面介绍和简例–以抓取雅卓app为例 我们在前面的文章中已经学习了如果使用python进行数据抓取. 但我们常常会遇到一种场景,就是想要获取的页面内容或者接 ...

  4. pythonurllib新浪微博_python模拟登录新浪微博抓取数据(cookielib和urllib2).doc

    HYPERLINK "/article/python/22972.html" /article/python/22972.html python模拟登录新浪微博抓取数据(cooki ...

  5. Java模拟登录并抓取数据

    问题: 最近做一个抓取数据的项目,发现网上很多资料不完备,或者按照代码执行不能真实爬取数据,自己特别根据自己的网站进行登录并进行数据爬取. 未登录 登录后,正常抓取数据截图(预期目标数据) 解决办法: ...

  6. java模拟新浪微博_Java模拟新浪微博登陆抓取数据

    前言: 兄弟们来了来了,最近有人在问如何模拟新浪微博登陆抓取数据,我听后默默地抽了一口老烟,暗暗的对自己说,老汉是时候该你出场了,所以今天有时间就整理整理,浅谈一二. 首先: 要想登陆新浪微博需要预登 ...

  7. 系统检测到您正在使用网页抓取工具访问_从网站抓取数据的3种最佳方法

    halo,大家好,我是特仑苏,今天呢给大家分享一些Python从网站抓取数据的一些方法,希望可以给大家带来一些帮助! 原作者:Octoparse团队 原出处:作品文(从网站抓取数据的3种最佳方法)/网 ...

  8. python登录新浪微博抓取微博内容_python机器登陆新浪微博抓取数据

    使用python机器登陆新浪微博抓取数据 1.[代码][Python]代码 # import 这边需要注意的是只有一个rsa这个模块是需要install的,其他的都是内置 import re , ur ...

  9. wget抓取数据,需要用户登录验证

    Niushop3.0电商系统,性价比之王!开牛店的第一选择! 在用wget抓取数据的时候,有的时候需要用户登录才能进行.这种情况下就需要时用cookie. 先看下面的代码:   wget --load ...

最新文章

  1. 【转】Maven Jetty 插件的问题(css/js等目录死锁)的解决
  2. 基于用户投票的排名算法(三):Stack Overflow
  3. arduino无源蜂鸣器歌曲编码_Arduino与无源蜂鸣器
  4. C#和java的语法区别
  5. 和transformjs一起摇摆
  6. MFC图形界面编辑工具
  7. python向excel隔行写数据_【Python】将每日新增数据写入Excel
  8. u盘数据恢复软件哪个好?免费软件有哪些?
  9. 计算机音乐代表人物,在你的周围,一定有许多名人吧!比如:故事大王xxx,电脑高手xxx,音乐家xxx……请你选择其中一...
  10. mysql查看时区 go时区问题
  11. 怎么安装linux操作系统
  12. 程序化广告欺诈流量过滤方法
  13. 淘宝 Android 端图片体验优化实践
  14. 【Java杂货铺】JVM#Java高墙之GC与内存分配策略
  15. 2016全球与中国市场DIN导轨式电源深度研究报告
  16. Linux服务器Anaconda安装Pytorch(注意,前方有大坑)
  17. JavaScript二级联动
  18. 全球及中国建筑设计行业规划布局与十四五竞争现状分析报告2021版
  19. 后羿 06 ‖ 风神
  20. [群晖]此套件需要您启动[pgsql-adapter.service]

热门文章

  1. 让深度学习进入移动端,蘑菇街在移动端的深度学习优化实践
  2. 手把手教你实现解密数独的小程序并部署到web端
  3. kotlin杂谈系列十二(Kotlin和Java的互操作)
  4. Tomcat是干嘛用的?企业级Tomcat部署实践及安全调优
  5. Spring Doc OpenAPI3.0 抛弃SpringFox拥抱SpringDoc
  6. 概率论学习二、样本空间与事件
  7. python公众号教学_Python微信公众号后台开发教程
  8. 数据库优化八大通用绝招
  9. Arcgis小技巧【1】——地理配准
  10. 架构师日常-团队管理