怎样抽取网页标记之间的正文

本文介绍如何利用WebBrowser控件实现网页导航,并通过IHTMLDocument2接口获取页面源代码及内联文本内容,提供了多种获取网页内容的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


添加webbrowser Controls组件


Insert OK Close。



添加导航代码

void CExtractTextDlg::OnButtonExplorer() 
{
	UpdateData(TRUE);
	if (!m_strUrl.IsEmpty())
	{
		
		COleVariant vtEmpty;
		//	m_WebBrowser1.Navigate(_T("F:\\test.html"), &vtEmpty, &vtEmpty,&vtEmpty, &vtEmpty);
		
		m_WebBrowser1.Navigate(m_strUrl, &vtEmpty, &vtEmpty,&vtEmpty, &vtEmpty);
		
	}
	
}
为使用IHTMLElement2,dlg头文件加入

#include <mshtml.h>

#include "webbrowser2.h"
void CExtractTextDlg::OnButtonExtract() 
{
	IHTMLDocument2*pDoc=(IHTMLDocument2*)m_WebBrowser1.GetDocument();
	IHTMLElement*pHTMLBodyElement=NULL;
	if(pDoc!=NULL)  
	{  
		HRESULT hr=pDoc->get_body(&pHTMLBodyElement);
		if(SUCCEEDED(hr)&&pHTMLBodyElement!=NULL)  
		{  
			
			
			BSTR b;
			pHTMLBodyElement->get_innerText(&b);
			CString strHtml(b);
			//自己添加
			m_strInnerText=strHtml;
			AfxMessageBox(m_strInnerText);
			UpdateData(FALSE);
			
		}	
	}	
}

另外一种方法

void CDlgebDlg::getcode()
{
/**
* @定义变量
	*/
	long     BufSize   = 100000L; 
	long     Size;
	
	FILE     *fp;
	IStream     *Stream; 
	HGLOBAL     hHTMLText; 
	ULARGE_INTEGER   size;
	IPersistStreamInit *psi; 
	IHTMLDocument2   *htm;
	
	/**
	* @获取指定网页的源代码
	*/
	htm    = (IHTMLDocument2*)m_WebBrowser1.GetDocument(); 
	htm->QueryInterface((REFIID)IID_IPersistStreamInit, (void**) &psi); 
	
	psi->GetSizeMax(&size); 
	hHTMLText = GlobalAlloc(GMEM_FIXED, BufSize);  
	
	if ((void*)NULL == hHTMLText )   
	{
		return;
	}
	
	memset((char*)hHTMLText,0,BufSize);
	CreateStreamOnHGlobal(hHTMLText, true, &Stream);
	
	psi->Save(Stream,    false);   
	Size   = strlen((char*)hHTMLText);   
	
	/**
	* @相关信息保存到指定文件中
	*/ 
	fp = fopen("a.txt","wt"); 
	fwrite((char*)hHTMLText,Size,1, fp); 
	fclose(fp);
	
//	AfxMessageBox((char*)hHTMLText);
	
	GlobalFree(hHTMLText); 
	psi->Release (); 
}

//其中GIVENFILE是文件名称,如a.txt.







void CDlgebDlg::OnButton5() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.GoHome();
}

void CDlgebDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.GoBack();
	
}

void CDlgebDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.GoForward();
	
}

void CDlgebDlg::OnButton4() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.Stop();
}



void CDlgebDlg::OnButton7() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER,
		NULL, NULL);

}

void CDlgebDlg::OnButton8() 
{
	// TODO: Add your control notification handler code here
	m_WebBrowser1.ExecWB(OLECMDID_PAGESETUP, OLECMDEXECOPT_PROMPTUSER,
		NULL, NULL);
	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值