枚举HTML元素及超链接


#include <mshtml.h>

INT EnumHtmlElement(IDispatch *pDispDoc, CStringArray &m_listTags, CStringArray &m_listHref)
{
  m_listTags.RemoveAll();
  m_listHref.RemoveAll();

  IHTMLDocument2* pHTMLDocument2 = NULL; 
  IHTMLElementCollection* pColl = NULL; 
  HRESULT hr; 
  LONG celem = 0; 
  
  if(pDispDoc)
    pDispDoc->QueryInterface( IID_IHTMLDocument2, (void**)&pHTMLDocument2 ); 
  if(pHTMLDocument2)
    pHTMLDocument2->get_all( &pColl ); 
  if(pColl)
    pColl->get_length( &celem );
  
  for ( int i=0; i< celem; i++ )
  {
    VARIANT varIndex; 
    varIndex.vt = VT_UINT; 
    varIndex.lVal = i; 
    VARIANT var2; 
    VariantInit( &var2 ); 
    IDispatch* pDisp = NULL;   
    hr = pColl->item( varIndex, var2, &pDisp );  
    if (hr == S_OK) 
    {    
      IHTMLElement* pElem = NULL;  
      hr = pDisp->QueryInterface( IID_IHTMLElement, (void **)&pElem ); 
      if ( hr == S_OK ) 
      {
        BSTR bstr;
        hr = pElem->get_tagName(&bstr);
        CString strTag = bstr;
        IHTMLImgElement* pImgElem = NULL;
        hr = pDisp->QueryInterface( IID_IHTMLImgElement, (void **)&pImgElem );
        if ( hr == S_OK )
        { 
          pImgElem->get_href(&bstr); 
          strTag += " - "; 
          strTag += bstr; 
          m_listHref.Add(bstr);
          pImgElem->Release(); 
        }
        else
        {
          IHTMLAnchorElement* pAnchElem = NULL; 
          hr = pDisp->QueryInterface( IID_IHTMLAnchorElement, (void **)&pAnchElem ); 
          if ( hr == S_OK ) 
          { 
            pAnchElem->get_href(&bstr); 
            strTag += " - "; 
            strTag += bstr; 
            m_listHref.Add(bstr);
            pAnchElem->Release(); 
          }
        }
        
        m_listTags.Add( strTag );  
        pElem->Release();
      } 
      pDisp->Release(); 
    }
  }
  
  if(pColl)
  {
    pColl->Release(); pColl = NULL;
  }
  
  if(pHTMLDocument2)
  {
    pHTMLDocument2->Release(); pHTMLDocument2 = NULL;
  }
  
  if(pDispDoc)
  {
    pDispDoc->Release(); 
    pDispDoc = NULL;
  } 

  return (INT)m_listTags.GetSize();
}

 

//在HTMLView中测试

void CWebViewView::OnDocumentComplete(LPCTSTR lpszURL) 
{
	// TODO: Add your specialized code here and/or call the base class

  LPDISPATCH pDisp = GetHtmlDocument();
  CStringArray m_listTags, m_listHref;
  if(EnumHtmlElement(pDisp, m_listTags, m_listHref) > 0)
  {
    TRACE(_T("\nTags\n"));
    for(INT_PTR i=0; i<m_listTags.GetSize(); i++)
    {
      TRACE(_T("%s\n"), (LPCTSTR)m_listTags[i]);
    }

    TRACE(_T("\nhref\n"));
    for(INT_PTR j=0; j<m_listHref.GetSize(); j++)
    {
      TRACE(_T("%s\n"), (LPCTSTR)m_listHref[j]);
    }
  }
  pDisp->Release();


	CHtmlView::OnDocumentComplete(lpszURL);
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值