C++ 提取網頁內容系列之一


標 題: C++ 提取網頁內容系列
作 者: itdef
鏈 接: http://www.cnblogs.com/itdef/p/4171179.html 

歡迎轉帖 請保持文本完整並注明出處

首先分析網頁就要下載網頁內容 這里給出了兩種方案

一種是使用MFC自帶函數

代碼如下:

int GetHttpFileData(CString strUrl,char* szDownloadHtmFileName)
{
	CInternetSession Session("Internet Explorer", 0);
	CHttpFile *pHttpFile = NULL;
	CString strData;
	CString strClip;
	int iRet = -1;

	if(szDownloadHtmFileName == NULL)
	{	
		cerr << "DownloadHtmFileName is NULL" << endl;
		Session.Close();
		return iRet;
	}

	ofstream of(szDownloadHtmFileName);
	if (of.bad())
	{
		cerr << "of create file error" << endl;
		Session.Close();
		return iRet;
	}

	try
	{
		pHttpFile = (CHttpFile*)Session.OpenURL(strUrl);
		while ( pHttpFile->ReadString(strClip) )
		{
			of << strClip;
		}
	}catch(CInternetException* pEx)
	{
		TCHAR pszError[64];
		pEx->GetErrorMessage(pszError, 64);
		cerr << __FUNCTION__ << pszError << endl;
		goto GetHttpFileData_EXIT;
	}

	iRet = 0;

GetHttpFileData_EXIT:
	Session.Close();
	of.close();

	return iRet;
}

這里我將下載內容寫入了一個文件存入硬盤。另外還需要注意的是 網頁文件下載的格式可能是寬字節 使用UTF8格式,這里需要將其轉換為GBK多字節。

int UTF8Str2GBK(const string& strUTF8,string& strGBK)
{
	int i = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
	WCHAR *wsz = NULL;
	TCHAR *tsz = NULL;
	int iRet = -1;

	wsz = new WCHAR[i+1];
	if( NULL == wsz)
	{
		goto UTF8Str2GBK_EXIT;
	}
	MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, wsz, i);

	i = WideCharToMultiByte(CP_ACP, 0, wsz, -1, NULL, 0, NULL, NULL);
	tsz = new TCHAR[i+1];
	if( NULL == tsz)
	{
		goto UTF8Str2GBK_EXIT;
	}
	WideCharToMultiByte(CP_ACP, 0, wsz, -1, tsz, i, NULL, NULL);
	
	strGBK = string(tsz);

	iRet = 0;
UTF8Str2GBK_EXIT:

	delete []wsz;
	delete []tsz;

	return iRet;
}

全部代碼見 http://www.oschina.net/code/snippet_614253_43732

效果圖見 http://www.cnblogs.com/itdef/p/4081963.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM