C#模拟登录,代码如下:
在使用前需要导入以下命名空间
using SHDocVw;//System/SHDocVw.dll
using mshtml;//microsoft.mshtml
SHDocVw.InternetExplorer ie = new InternetExplorer();
ie.Visible = true;
Object nullArg = null;
String URL = xmlManager.getXmlData("gotoURL"); //从xml文件读取配置参数
URL = URL.Replace("#", "&") + phoneno;
ie.Navigate(URL, ref nullArg, ref nullArg, ref nullArg, ref nullArg);
System.Threading.Thread.Sleep(int.Parse(xmlManager.getXmlData("beforeLOADSLEEP")));
mshtml.IHTMLDocument2 DOM = (mshtml.IHTMLDocument2)ie.Document;
mshtml.IHTMLInputTextElement txtUserName = ((mshtml.IHTMLInputTextElement)DOM.all.item(xmlManager.getXmlData("inputUSER"), null)); //inputUSER应页面表单元素同名
if (txtUserName != null)
{
txtUserName.value = user;
}
mshtml.IHTMLInputTextElement txtPass = ((mshtml.IHTMLInputTextElement)DOM.all.item(xmlManager.getXmlData("inputPASSWORD"), null));
if (txtPass != null)
{
txtPass.value = pass;
}
mshtml.HTMLInputElement btnLogin = (mshtml.HTMLInputElement)DOM.all.item(xmlManager.getXmlData("inputBUTTON"), null); //inputBUTTON应页面表单元素同名,图片button也可用此方式,主要是面向提交对象
if (btnLogin != null)
{
System.Threading.Thread.Sleep(int.Parse(xmlManager.getXmlData("afterLOADSLEEP"))); //线程休睡
btnLogin.click();
}
下面整理下,以上代码中需要注意的几点:
1、URL.Replace("#", "&") ---在xml文件里不能包含‘&’符,否则在C#读取XML时会提示格式不对。
2、 ((mshtml.IHTMLInputTextElement)DOM.all.item(xmlManager.getXmlData("inputUSER"), null)); ---此处理inputUSER在此已经模拟成表单元素了,因为要模拟登录。所以必需和要登录的页面元素一一对应。
3、System.Threading.Thread.Sleep ---在调用IE程序时,应对C#程序的当前线程作相应的休睡。
这个休睡是很有必要的,因为IE在启动时需要一些时间和资源,速度跟不上C#程序,所以C#程序要做相应的休睡。否则会报异常("对 COM 组件的调用返回了错误 HRESULT E_FAIL。 ")。