#include <comdef.h>
#include <mshtml.h>
#pragma warning(disable : 4146) //see Q231931 for explaintation
#import <mshtml.tlb>  no_auto_exclude
CString GetHtmlLinks(CString strHtmlFile,const int nType=0,int nLoopNum=1 )
{
CCriticalSection g_cs;
//declare our MSHTML variables and create a document
MSHTML::IHTMLDocument2Ptr pDoc;
MSHTML::IHTMLDocument3Ptr pDoc3;
MSHTML::IHTMLElementCollectionPtr pCollection;
MSHTML::IHTMLElementPtr pElement;
    
HRESULT hr = CoCreateInstance(CLSID_HTMLDocument,NULL,CLSCTX_INPROC_SERVER,IID_IHTMLDocument2,(void**)&pDoc); //put the code into SAFEARRAY and write it into document
SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, 1);
VARIANT *param;
bstr_t bsData = (LPCTSTR)strHtmlFile;
hr = SafeArrayAccessData(psa, (LPVOID*)&param);
param->vt = VT_BSTR;
param->bstrVal = (BSTR)bsData;
    g_cs.Lock();
hr = pDoc->write(psa);
hr = pDoc->close();

SafeArrayDestroy(psa);
g_cs.Unlock();

//I'll use IHTMLDocument3 to retrieve tags. Note it is available only in IE5+
//If you don't want to use it, u can just run through all tags in HTML
//(IHTMLDocument2->all property)
pDoc3 = pDoc;

//display HREF parameter of every link (A tag) or IMG parameter of every link (SRC tag) if(nType==0)
pCollection = pDoc3->getElementsByTagName(L"A");
else
pCollection = pDoc3->getElementsByTagName(L"IMG");    CString strLinkOutput;

int nRandNum=rand()%nLoopNum; for(long i=0; i<pCollection->length; i++)
{
pElement = pCollection->item(i,(long)0);
if(pElement != NULL)
{
//second parameter says that you want to get text inside attribute as is
if(nType==0)
strLinkOutput=(LPCTSTR)bstr_t(pElement->getAttribute("href", 2));
else
strLinkOutput=(LPCTSTR)bstr_t(pElement->getAttribute("src", 2));
}
if(i==nRandNum)
break;
}
return strLinkOutput;
}

解决方案 »

  1.   

    兄台,我根本没通过thread传参数!我就是在thread里面执行。带上个简单参数。GetHtmlLinks("<a href=http://test.com>",0,1);
      

  2.   

    线程需要初始化COM
    在线程开始加上
    CoInitialize(NULL);
      

  3.   

    你必须在该线程中调用CoInitializeEx。
    注意:CoInitializeEx函数只对调用线程有效。你在主线程中调用过所以在
    主线程中OK,但没有在你的线程中调用过,所以有问题。
      

  4.   

    CoInitializeEx初试化COM线程支持,对于多线程调用许申明相关参数
      

  5.   

    按照dai2255()测试成功。非常感谢。同样感谢verybigbug() 和xf2002xf(xf2002xf) 的回答。我提高了帖子分数到100,分数已加上。再次感谢!! have a good day. :P