C# 自动登录网页,浏览页面【转载】

需求:客户的数据同时存在在另外一个不可控的系统中,需要和当前系统同步。

思路:自动登录另外一个系统,然后抓取数据,同步到本系统中。

技术点:模拟用户登录;保存登录状态;抓取数据

/// <summary>
        /// visit the target url
        /// </summary>
        /// <param name="targetURL"></param>
        /// <param name="cc">this is for keeping cookies and sessions</param>
        /// <param name="param">this is the data need post inside form</param>
        /// <returns>html page</returns>
        public static string PostAndGetHTML(string targetURL,CookieContainer cc,Hashtable param)
        {
            //prepare the submit data
            string formData = "";
            foreach (DictionaryEntry de in param)
            {
                formData += de.Key.ToString() + "=" + de.Value.ToString() + "&";
            }
            if (formData.Length > 0)
                formData = formData.Substring(0, formData.Length - 1); //remove last ‘&‘

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(formData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //post
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";

            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);

            newStream.Close();

            request.CookieContainer = cc;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            cc.Add(response.Cookies);
            Stream stream = response.GetResponseStream();
            string result = new StreamReader(stream, System.Text.Encoding.Default).ReadToEnd();
            return result;
        }

        public static DataTable ConvertToDT(DataTable dt, string tableHTML)
        {

            int lastTD = tableHTML.ToLower().LastIndexOf("</td>");
            int firstRow = tableHTML.ToLower().IndexOf("<tr") + 3;//after ""<tr
            int index = tableHTML.ToLower().IndexOf("<tr", firstRow) + 3;//after ""<tr
            while (index < lastTD)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string value = "";
                    int startTD = tableHTML.ToLower().IndexOf("<td", index) + 3;//after "<td"
                    int endTD = tableHTML.ToLower().IndexOf("</td>", startTD);
                    if (endTD < 0)
                        break;
                    string tdStr = tableHTML.Substring(startTD, endTD - startTD);

                    //remove <> and others
                    tdStr = tdStr.Replace("&nbsp;", "").Replace("\t", "").Replace("\r", "");
                    string[] v = tdStr.Split(‘<‘, ‘>‘);
                    for (int j = 0; j < v.Length; j++)
                    {
                        j++;
                        if (v[j].Trim() != "")
                        {
                            value = v[j].Trim();
                            break;
                        }
                    }
                    //
                    dr[i] = value;
                    index = endTD;
                }
                dt.Rows.Add(dr);

            }
            return dt;
        }

这一个是调用的例子:先登录,在查询。 实际中这个逻辑可能有很多步骤

CookieContainer cc = new CookieContainer();//this is for keep the Session and Cookie
            Hashtable param = new Hashtable();//this is for keep post data.

            string urlLogin = "http://demo.server//login.asp";
            //do find the elementId that needed. check the source of login page can get this information
            param.Add("User", "xxx");
            param.Add("Password", "xxxx");
            string result =GrabHelper.PostAndGetHTML(urlLogin, cc, param);
            //check result, whether login success

            //if login success, goto the target url, and input some value.
            string url2 = " http://demo.server/query.asp?id=1";// need change. special logic
            param.Clear();
            //param.Add("SearchAreaId","JobId")
            result = GrabHelper.PostAndGetHTML(url2, cc, new Hashtable());
            //ConvertToDT the html or do something others
时间: 2024-08-27 21:50:30

C# 自动登录网页,浏览页面【转载】的相关文章

python3实现自动登录网页版QQ

最近一直想搞一个自动登录的程序,今天琢磨了一会,也搞出来了.不过功能不多.但是对我来说,也是一个小小的进步吧.知识日积月累,自然就会的多了.废话不多说,代码最实际了. 环境: 系统: windows10 IDE开发工具:Pycharm Professional 模块: selenium,time 安装selinium: pip install selenium 浏览器驱动配置: Firefox驱动: GeckoDriver 1. 相关链接: GitHub:[github地址](https://g

AAuto 自动登录网页

import win.ui; import web.form; /*DSG{{*/ var winform = win.form(parent=...; min=1;bottom=249;scroll=1;right=349;text="AAuto Form";max=1 ) winform.add(  ) /*}}*/ //创建web窗体 var wb = web.form( winform ); //打开目标网站 wb.go("http://xxx.com/public/

python 自动登录网页

语言:python 浏览器:chrome 工具:chrome控制台 #!/usr/bin/python # coding: GBK import urllib,urllib2,httplib,cookielib import time import random def auto_login(url,name,pwd): url_login = "http://my.jjwxc.net/login.php" cookie = cookielib.CookieJar() cj = url

获取全局上下文(getApplicationContext)_创建Shared Preference工具类_实现自动登录

===========================获取全局上下文(getApplicationContext)======================== 1.在com.example.autologin.myapplication包中创建Myapplication extends Application 代码: 1 public class Myapplication extends Application 2 { 3 private static Context context; 4

Python3.x爬虫教程:爬网页、爬图片、自动登录

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文将使用Python3.4爬网页.爬图片.自动登录.并对HTTP协议做了一个简单的介绍.在进行爬虫之前,先简单来进行一个HTTP协议的讲解,这样下面再来进行爬虫就是理解更加清楚. 一.HTTP协议 HTTP是Hyper Text Transfer Protocol(超文本传输协议)的缩写.它的发展是万维网协会(World Wide Web Consortium)和Internet工作

网页自动登录,自动填充表单代码

实现自动登录某网站,并且登录完成后跳转到指定的页面.然后进行表单的自动填充表单提交 .类型于小型的发帖机 哈哈 (看官在看下面代码的时候,把记得把下面的链接改下) public partial class Form1 : Form { public Form1() { InitializeComponent(); webBrowser1.Navigate("www.tiantianit.com"); } private void webBrowser1_DocumentComplete

php登录页面cookie自动登录及验证

<?php //cookie实现自动登录 error_reporting(0);// 关闭错误报告(浏览页面出现notice可用此法消除) $user = $_POST['username'];$pwd = $_POST['password'];if ($user!=''&&$pwd!=''){if($_POST['remmber']==1){ header("Location:http://localhost/homework/login.php"); //转到

利用activeX控件在网页里自动登录WIN2003远程桌面并实时控制

首先要自己配置并打开受控端的WEB远程桌面服务,这个在"添加/删除windows组件"里有,我只在windows 2003 server里试过,没试过XP.下面我们在客户端安装微软提供的远程桌面客户端控件,这个控件的安装包可以在windows2003服务器的system32目录下找到,你可以放到web虚拟目录下供客户端下载. 远程桌面客户端控件安装完成后,在客户端计算机打开frontpage2003,创建一个新页面,选"插入"->插入WEB组件->自定义

Laravel 登录后跳转回登录前浏览的页面

一.经过 Auth 中间件检查后跳转至登录页面 也就是没有通过 auth 中间件的认证检查,被 auth 中间件拦截后跳转至登录页面.这种情况下,Laravel 默认会在用户登录成功后自动跳转回登录前浏览的页面.auth 中间件是怎么做到的? 打开 auth 中间件文件: // vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php protected function authenticate(array