利用CHtmlView填充表单和模拟单击事件,欢迎交流指点

whucv 2012-08-09 08:50:31
本人新手,没有做过网络方面的程序,见论坛上很多人在问这个问题,自己查找了一些资料,编写了如下程序,不会用CHttpFile等,只能利用最简单的一些东西。如果有更好的思路,欢迎指点。
http://blog.csdn.net/whucv/article/details/7848858
本例在已知账号和密码情况下,以自动登录renren网为例,其中获取表单元素value、type等值是审查人人网登录首页源代码得到。
1、新建单文档应用程序,选中为CHtmlView视图基类。
2、在view头文件加入下面代码
#include "mshtml.h" //使用IHTMLDocument2接口
#include <atlbase.h> //使用CComVariant

extern CComModule _Module;
#include "atlcom.h" //CComDispatchDriver需要,而且在它之前需加上CComModule _Module;
3、添加填充表单函数填充用户名和密码
void CAutoLoginView::AutoFillForm(IHTMLDocument2 *pIHTMLDocument2, CComVariant username, CComVariant password)
{
if( !pIHTMLDocument2 )return;

HRESULT hr;
CComBSTR bstrTitle;
pIHTMLDocument2->get_title( &bstrTitle );//取得文档标题

CComQIPtr< IHTMLElementCollection > spElementCollection;
hr = pIHTMLDocument2->get_forms( &spElementCollection );//取得表单集合
if ( FAILED( hr ) )
{
AfxMessageBox("获取表单的集合 IHTMLElementCollection 错误");
return;
}
long nFormCount=0;//取得表单数目
hr = spElementCollection->get_length( &nFormCount );
if ( FAILED( hr ) )
{
AfxMessageBox("获取表单数目错误");
return;
}

for(long i=0; i<nFormCount; i++) //遍历表单
{
IDispatch *pDisp = NULL;//取得第 i 项表单
hr = spElementCollection->item( CComVariant( i ), CComVariant(), &pDisp );
if ( FAILED( hr ) )continue;

CComQIPtr< IHTMLFormElement > spFormElement = pDisp;
pDisp->Release();

long nElemCount=0;//取得表单中 域 的数目
hr = spFormElement->get_length( &nElemCount );
if ( FAILED( hr ) )continue;

for(long j=0; j<nElemCount; j++)
{
CComDispatchDriver spInputElement;//取得第 j 项表单域
CComVariant vName,vVal,vType;//取得表单域的名,值,类型
hr = spFormElement->item( CComVariant( j ), CComVariant(), &spInputElement );
if ( FAILED( hr ) )continue;
hr = spInputElement.GetPropertyByName(L"name", &vName);
if(vName == (CComVariant)"email")
{
vVal = username;
spInputElement.PutPropertyByName(L"value",&vVal);
}
if(vName == (CComVariant)"password")
{
vVal = password;
spInputElement.PutPropertyByName(L"value",&vVal);
}

}
//提交表单
//spFormElement->submit();

}

}


4、添加工具栏或菜单栏响应
void CAutoLoginView::OnLoginRenren() 
{
// TODO: Add your command handler code here
Navigate2("http://www.renren.com/",NULL,NULL);
IHTMLDocument2* pHtmlDoc2=(IHTMLDocument2*)GetHtmlDocument();
CComVariant email =L"123@qq.com"; // construct from a LPCSTR 账号
CComVariant password=L"123456"; //密码
AutoFillForm(pHtmlDoc2,email,password);
AutoLogin();
}

...全文
169 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

3,055

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC HTML/XML
社区管理员
  • HTML/XML社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧