CHtmlView获取网页所有元素的连接和名字

本文提供了一段使用C++实现的代码片段,用于从HTML文档中获取所有链接,包括链接的URL和文本内容。
BOOL   MyDlg::GetAllLinks(CMyHtmlView   *pView) 
{ 
IHTMLDocument2   *   pDoc   =   NULL; 
IHTMLElementCollection     *   pAllElem   =   NULL; 
IHTMLElement   *pElem   =   NULL; 
IHTMLAnchorElement   *   pAnchor   =   NULL; 
IHTMLElement*   ptext; 
long   p; 
BSTR   bstrSrc; 
VARIANT   name; 
name.vt   =   VT_I4; 

try{ 
pDoc   =   (IHTMLDocument2*)(pView-> GetHtmlDocument()); 
if(pDoc!=NULL) 
{ 
pDoc-> get_links(&pAllElem); 

if(pAllElem!=NULL) 
{ 
pAllElem-> get_length(&p); 
if(p> 0) 
{ 
for(int   i=0;   i <p;   i++) 
{ 
name.lVal   =   i; 
if(pAllElem-> item(name,   name,   (LPDISPATCH*)&pElem)==S_OK) 
{ 
if(pElem   !=   NULL) 
{ 
pElem-> QueryInterface(&pAnchor); 
if(pAnchor!=NULL) 
{ 
pAnchor-> get_href(&bstrSrc); 
CString   sHref(bstrSrc);     //url 
SysFreeString(bstrSrc); 

pAnchor-> QueryInterface(&ptext); 
ptext-> get_innerText(&bstrSrc); 
CString   sText(bstrSrc);   //text 
SysFreeString(bstrSrc); 
ptext-> Release(); 

pAnchor-> Release(); 
pAnchor   =   NULL; 
} 
pElem-> Release(); 
pElem   =   NULL; 
} 
} 
} 
} 
} 
} 
}catch(...){} 

try{ 
if(pDoc   !=   NULL) 
pDoc-> Release(); 
if(pAllElem   !=   NULL) 
pAllElem-> Release(); 
}catch(...){} 

return   TRUE; 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值