目标:从一个表元素中获得第一个链接地址,并在新窗口中打开
测试地址:http://www.baidu.com/s?wd=%CD%F8%D2%D7
难点:如何获得表,接着在表中得到<a>元素,然后得到链接地址
思路:1.从CHtmlView中获得IHTMLDocument2接口,通过get_all()函数得到网页元素集合ITHMLElementCollection,通过item()函数,用表的ID或者表名获得IHTMLTable,用get_rows()函数获取表的第一行的网页元素的集合IHTMLElementCollection(这个集合内没有<a>标签),通过item()函数获取第一个IHTMLElement元素,用get_all()函数获取该元素内的所有元素的集合IHTMLElementCollection(这个集合 内有<a>标签),用tags函数获取<a>的元素集合IHTMLElementCollection,通过item()函数获取第一个IHTMLAnchorElement元素,使用get_href()函数获取链接。简单的图就是:
CHtmlView->IHTMLDocument2->ITHMLElementCollection->IHTMLTable->IHTMLElementCollection->IHTMLElement->IHTMLElementCollection->IHTMLElementCollection->IHTMLAnchorElement
(得到一个链接而已,真丫的累人!)
大致的代码如下:
//其中hr每次执行完之后需要走检测
HRESULT hr;
CComPtr<IDispatch> pDisp;
pDisp = GetHtmlDocument();
CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2 > pDoc = pDisp;
CComQIPtr <IHTMLElementCollection> pElementCollection;
hr = pDoc->get_all(&pElementCollection);
IDispatch *pDispatch = NULL;
hr = pElementCollection->item(CComVariant( "1" ), CComVariant(),&pDispatch);//1是表的名字或者ID
CComQIPtr <IHTMLTable> pTable = pDispatch;
pDispatch->Release();
CComQIPtr <IHTMLElementCollection> pElementCollection1;
hr = pTable->get_rows(&pElementCollection1);
hr = pElementCollection1->item(CComVariant( 0 ), CComVariant(),&pDispatch);
CComQIPtr <IHTMLElement> pElement = pDispatch;
hr = pElement->get_all(&pDispatch);
CComQIPtr <IHTMLElementCollection> pElementCollection2 = pDispatch;
hr = pElementCollection2->tags(CComVariant("a"), &pDispatch);
CComQIPtr <IHTMLElementCollection> pElementCollection3 = pDispatch;
hr = pElementCollection3->item(CComVariant( 0 ), CComVariant(),&pDispatch);
CComQIPtr <IHTMLAnchorElement> pElement1 = pDispatch;
BSTR vName;
pElement1->get_href(&vName);
CString str1 = (char *)_bstr_t(vName);
OpenNewLinks(str1);
void CMIEView::OpenNewLinks(CString url)
{
AfxGetApp()->m_pMainWnd->SendMessage(WM_COMMAND,(WPARAM)ID_FILE_NEW);
CMainFrame *pFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;
CMDIChildWnd *pChild;
CMIEView *pView;
pChild = (CMDIChildWnd *) pFrame->GetActiveFrame();
pView = (CMIEView *) pChild->GetActiveView();
pView ->Navigate2(url);
}