打开网页表元素中的链接,并在新窗口中打开

目标:从一个表元素中获得第一个链接地址,并在新窗口中打开

测试地址: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); 

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值