CHtmlView 浏览器 开发 遍历 页面表单DOM元素

最近学习 定制浏览器开发,可以使用 CHtmlView 来实现。

又碰到获取表单和给表单赋值 的问题,这样就可以实现自动提交表单的 第一步了。

 

下面,以 baidu 首页为例,分析知道 要获取 搜索框 <input name="wd" ...>

我们 重写 OnDocumentComplete 函数,并且在其中处理。 

 

void CMyHtmlView::OnDocumentComplete(LPCTSTR lpszURL)

{
TRACE("OnDocumentComplete()\n");
IHTMLDocument2* pHtmlDoc2 =(IHTMLDocument2*)CHtmlView::GetHtmlDocument();
//现在只考虑一个 frame 的情况
CComQIPtr< IHTMLElementCollection > spElementCollection;
CComVariant vppValue = _T("博客"),vppName = _T("wd");
if(pHtmlDoc2)
{
HRESULT hr = S_OK;
hr = pHtmlDoc2->get_forms(&spElementCollection);
if(FAILED(hr))
{
return;
}
long nFormCount = 0; //取得表单数
hr = spElementCollection->get_length( &nFormCount );
if(FAILED(hr))
{
pHtmlDoc2->Release();
return;
}
for(long i=0;i<nFormCount;i++)
{
IDispatch* pDisp = NULL;
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;
hr = spFormElement->item(CComVariant(j),CComVariant(),&spInputElement);
if(FAILED(hr)) continue;
CComVariant vName,vVal,vType;
hr = spInputElement.GetPropertyByName(L"name",&vName);
if(vName == vppName)
{
                    spInputElement.PutPropertyByName( L"value", &vppValue);
}
               
}
}
}
CHtmlView::OnDocumentComplete(lpszURL);
}

 

 这段代码将会实现在 打开 www.baidu.com 时就自动填写 搜索关键字框 为 "博客",神奇吧,O(∩_∩)O~。

 

我们还要实现 CHtmlView 调用 javascript 实现自动提交,一步一个脚印,验证我们的执着...... 

 

 

posted @ 2011-07-06 11:02  我在地球  阅读(863)  评论(0编辑  收藏  举报