<table id="Test_Table"><br /><thead><br /><tr><br /><th><span>姓名</span></th><br /><th><span>性別</span></th><br /></tr><br /></thead><br /><tbody><br /><tr><br /><td>ZDZ</td><br /><td>男</td><br /></tr><br /></tbody><br /></table>
表格內容如上,第一行是 姓名, 性別,第二行是zdz , 男,
現要獲得第二行第二列元素的內容,即"男",介面順序依次是
IHTMLTable ---> IHTMLTableRow ---> IHTMLElement
代碼如下:
CString getInfo()<br />{<br />// TODO: 在此添加控制項通知處理常式代碼<br />CString strInfo;<br />HRESULT hr;<br />IDispatch *pDisp;<br />pDisp = m_webBrowser.get_Document(); // 擷取webbrowser控制項文檔介面<br />IHTMLDocument2* pDoc;<br />hr = pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&pDoc ); // 擷取操作介面的文檔介面<br />IHTMLElementCollection* pColl = NULL;<br />hr = pDoc->get_all( &pColl ); // 擷取網頁元素集合<br />VARIANT index;<br />VARIANT varID;<br />V_VT(&index) = VT_I4;<br />V_I4(&index) = 0;<br />varID = StringToVariant("Test_Table"); // 表格元素ID<br />hr = pColl->item(varID, index, &pDisp); // 獲得表格位置<br />if ( (hr == S_OK) && (pDisp != NULL) )<br />{<br />IHTMLTable * pTable; // 獲得表格元素介面<br />hr = pDisp->QueryInterface(IID_IHTMLTable,(void **)&pTable );<br />if ( (hr == S_OK) && (pTable != NULL) )<br />{<br />IHTMLElementCollection* pColl2 = NULL;<br />pTable->get_rows(&pColl2); // 擷取表格行<br />IDispatch* pDisp2;<br />V_I4(&index) = 1;<br />hr = pColl2->item( index,index, &pDisp2 ); // 擷取第2行位置<br />if ( (hr == S_OK) && (pDisp2 != NULL) )<br />{<br />IHTMLTableRow* pRow; // 擷取行元素介面<br />hr = pDisp2->QueryInterface(IID_IHTMLTableRow,(void **)&pRow);<br />if( (hr == S_OK) && (pRow != NULL) )<br />{<br />IHTMLElementCollection* pColl3 = NULL;<br />pRow->get_cells(&pColl3); // 擷取格子項目<br />IDispatch* pDisp3;<br />V_I4(&index) = 1;<br />hr = pColl3->item( index,index, &pDisp3 ); // 擷取第2行第2格元素<br />if ( (hr == S_OK) && (pDisp2 != NULL) )<br />{<br />IHTMLElement* pElem; // 擷取元素介面<br />hr = pDisp3->QueryInterface(IID_IHTMLElement,(void **)&pElem);<br />if( hr == S_OK )<br />{<br />BSTR bstr = SysAllocString(L"");<br />pElem->get_innerText(&bstr); // 擷取該表格元素的文本資訊<br />strInfo = bstr;<br />pElem->Release();<br />}<br />pDisp3->Release();<br />}<br />pRow->Release();<br />}<br />pDisp2->Release();<br />}<br />pTable->Release();<br />}<br />pDisp->Release();<br />}<br />pDoc->Release();<br />pColl->Release();<br />return strInfo;<br />}