2010年7月6日 星期二

[C#] 自動登入/控制網頁

 

這是工作上所要用到的一個功能,第一次實做 IE 的自動登入。

 

string IE_ID = "guest"; //帳號部分
string IE_PW = "qkqk"; //密碼
mshtml.IHTMLDocument2 IE__DOC;  //網頁內容
mshtml.HTMLInputElementClass IE_INPUT; //輸入 Tag
SHDocVw.InternetExplorer IE_AUTO_OPEN_IE = null; //IE 視窗
object missing = null; //開起IE navigate用

if (IE_AUTO_OPEN_IE == null)
{
    IE_AUTO_OPEN_IE = new SHDocVw.InternetExplorer();
    IE_AUTO_OPEN_IE.Visible = true;
    IE_AUTO_OPEN_IE.Navigate("http://www.kimo.com.tw", ref missing, ref missing, ref missing, ref missing);

    while (IE_AUTO_OPEN_IE.StatusText.IndexOf("完成") == -1)
    {
        Application.DoEvents();
    }

    //開始處理
    IE__DOC = (mshtml.IHTMLDocument2)IE_AUTO_OPEN_IE.Document;
    foreach (mshtml.IHTMLElement MyElement in IE__DOC.all)
    {
        if (MyElement.tagName == "INPUT")
        {
            //轉型
            IE_INPUT = ((mshtml.HTMLInputElementClass)MyElement);

            //帳號
            if (IE_INPUT.name == "UserID")
            {
                IE_INPUT.value = IE_ID;
            }

            //密碼
            if (IE_INPUT.name == "UserPass")
            {
                IE_INPUT.value = IE_PW;
            }

            //登入
            if (IE_INPUT.value == "Login")
            {
                IE_INPUT.click();
            }
        }
    }

    while (true)
    {
        if (IE_AUTO_OPEN_IE.Busy == false && IE_AUTO_OPEN_IE.ReadyState == SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
        {
            break;
        }
        System.Threading.Thread.Sleep(500);
    }

    if (true)
    {
         Application.DoEvents();
        IE__DOC = (mshtml.IHTMLDocument2)IE_AUTO_OPEN_IE.Document;

        foreach (mshtml.IHTMLElement MyElement in IE__DOC.all)
        {
            if (MyElement.tagName == "INPUT")
            {
                //轉型
                IE_INPUT = ((mshtml.HTMLInputElementClass)MyElement);
                if (IE_INPUT.name == "UnitNo")
                {
                    IE_INPUT.value = textBox3.Text.Trim();
                }
            }
        }

1 則留言:

  1. 請問碰上頁面中有iframe,且此iframe是由Ajax產生的,有辦法解決嗎?

    回覆刪除