如何提取网页中所有链接
见过“网际快车”的“使用网际快车下载全部链接”这个功能吗?想实现它,我们可以这样做:
IE有几个有用的接口,我们可以用它来提取网页所有链接。一、基本原理
首先是用IHTMLDocument2的get_links,来获取IHTMLElementCollection接口,再通过IHTMLElementCollection来获取IHTMLAnchorElement,而IHTMLAnchorElement接口的get_href就是我们想要的,通过循环获取,我们就可以得到网页的所有链接了!
二、具体代码
{
TCHAR HostName[2*MAX_PATH];
CComPtr<IDispatch> spDispatch;
CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> pDoc2;
CComPtr<IHTMLElementCollection> pElementCol;
CComPtr<IHTMLAnchorElement> pLoct;
// TODO: Add your control notification handler code here
int n = m_LinksList.GetItemCount();//GetCount();for (int i = 0; i < n; i ++){
IWebBrowser2 *pBrowser = (IWebBrowser2 *)m_LinksList.GetItemData(i);
if (pBrowser){
pBrowser->Release();
}
}m_LinksList.DeleteAllItems();
m_LinksNum = 0;
Log("**************************************************************");
Log(" ");if (m_spSHWinds){
int n = m_spSHWinds->GetCount();
for (int i = 0; i < n; i++){
_variant_t v = (long)i;
IDispatchPtr spDisp = m_spSHWinds->Item(v);
SHDocVw::IWebBrowser2Ptr spBrowser(spDisp); //生成一个IE窗口的智能指针
if (spBrowser){if (SUCCEEDED(spBrowser->get_Document( &spDispatch)))
pDoc2 = spDispatch;
if(pDoc2!=NULL)
{
if (SUCCEEDED(pDoc2->get_links(&pElementCol)))
{
// AfxMessageBox("IHTMLElementCollection");
long p=0;
if(SUCCEEDED(pElementCol->get_length(&p)))
if(p!=0)
{
m_LinksNum = m_LinksNum+p;
UpdateData(FALSE);for(long i=0;i<=(p-1);i++)
{BSTR String;
_variant_t index = i;
if(SUCCEEDED(pElementCol->item( index, index, &spDispatch)))
if(SUCCEEDED(spDispatch->QueryInte易做图ce( IID_IHTMLAnchorElement,(void **) &pLoct)))pLoct->get_href(&String);
ZeroMemory(HostName,2*MAX_PATH);
lstrcpy(HostName,_bstr_t(String));
m_LinksList.InsertItem(i,HostName);
m_LinksList.SetCheck(i,TRUE);
pLoct->get_hostname(&String);
ZeroMemory(HostName,2*MAX_PATH);
lstrcpy(HostName,_bstr_t(Strin
补充:软件开发 , C语言 ,