深入敌后_ / MFC / 使用MSHTML::IHTMLDocument...接口获取htm...

0 0

   

使用MSHTML::IHTMLDocument...接口获取html文件中的所有链接

2012-04-27  深入敌后_
这段代码读取一个本地的HTML文件并将获取到的所有链接显示在一个ListBox里面:

void CTestDlg::OnBgo() 
{
UpdateData();
CWaitCursor wait;
if(m_csFilename.IsEmpty()){
AfxMessageBox(_T("Please specify the file to parse"));
return;
}
CFile f;

//let's open file and read it into CString (u can use any buffer to read though
if (f.Open(m_csFilename, CFile::modeRead|CFile::shareDenyNone)) {
m_wndLinksList.ResetContent();
CString csWholeFile;
f.Read(csWholeFile.GetBuffer(f.GetLength()), f.GetLength());
csWholeFile.ReleaseBuffer(f.GetLength());
f.Close();

//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)csWholeFile;
hr = SafeArrayAccessData(psa, (LPVOID*)&param);
param->vt = VT_BSTR;
param->bstrVal = (BSTR)bsData;
hr = pDoc->write(psa);
hr = pDoc->close();
SafeArrayDestroy(psa);

//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) in ListBox
pCollection = pDoc3->getElementsByTagName(L"A");
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
m_wndLinksList.AddString((LPCTSTR)bstr_t(pElement->getAttribute("href", 2)));
}
}
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。如发现有害或侵权内容,请点击这里 或 拨打24小时举报电话:4000070609 与我们联系。

    猜你喜欢

    0条评论

    发表

    请遵守用户 评论公约

    类似文章
    喜欢该文的人也喜欢 更多