您的位置:首页 > Web前端 > HTML

MFC使用WebBrowser控件访问HTML页面DOM

2012-10-08 20:01 597 查看
我们经常会将一些数据写入HTML页面中,以便使用。例如:<input type="hidden" name="RoadPointsArray" id="LanLonPoints" value="" />,通过JavaScript得到的一些结果暂时放入id为LanLonPoints的value属性中,然后我们要在MFC中访问这个网页中的数据并进行一些处理,这时就需要得到网页的DOM来获取它们的属性值。

具体方法如下(贴出完整代码):

m_WebBrowser是WebBrowser控件的关联变量,同时在头文件中要加上#include <MsHTML.h>以包含那些接口

void CDemoDlg::OnBnClickedButtonGetwebdata()
{
CString allPointData;

IDispatch *pDisp = m_WebBrowser.get_Document();
IHTMLDocument2* pDocument;
IHTMLElementCollection* pCollection;

pDisp->QueryInterface(IID_IHTMLDocument2,(void**)&pDocument);
HRESULT hr;
hr = pDocument->get_all(&pCollection);
if( hr == S_OK )
{
long celem;
hr = pCollection->get_length(&celem);   //得到所有节点的个数用以遍历
if( hr == S_OK )
{
VARIANT varIndex, var;
for ( int i = 0; i < celem; i++ )
{
varIndex.vt = VT_UINT;
varIndex.lVal = i;
VariantInit(&var);
hr = pCollection->item(varIndex,var,&pDisp);
if ( hr == S_OK )
{
IHTMLElement *pElement;
hr = pDisp->QueryInterface(IID_IHTMLElement,(void**)&pElement);
if ( hr == S_OK )
{
CString pointData,id;
BSTR bs;
pElement->get_id(&bs);
id = CString(bs);
if ( id == _T("LanLonPoints") )
{
IHTMLInputElement* input;
hr = pDisp->QueryInterface(IID_IHTMLInputElement,(void**)&input);
input->get_value(&bs);   //将id为LanLonPoints中的value值赋给bs
pointData = CString(bs);
allPointData = pointData;
}
}
}
}
}
}
parseRoadData(allPointData);
}


通过以上方法我们就可以得到所需的数据了,然后再根据需要进行处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: