Advertisement

C++抓网页/获取网页内容

阅读量:

#include<windows.h>

#include<Wininet.h>

#include

#include

#include

#pragma comment(lib,"WinInet.lib")

using namespace std;

int main()

{

HINTERNET hINet, hHttpFile;

char szSizeBuffer[32];

DWORD dwLengthSizeBuffer = sizeof(szSizeBuffer);

hINet等于InternetOpen("IE6.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );并且对InternetOpen进行WININET.DLL初始化。

string url = "http://www.sina.com"; //抓新浪网

if ( !hINet )

{

cout << "InternetOpen fail" << endl;

return 1;

}

hHttpFile = InternetOpenUrl(hINet, url.c_str(), NULL, 0, 0, 0); //该函数通过网络连接并从服务器接收数据

if(!hHttpFile)

{

cout << "error open url" << endl;

return 1;

}

BOOL bQuery = HttpQueryInfo(hHttpFile,

HTTP_QUERY_CONTENT_LENGTH,

szSizeBuffer,

&dwLengthSizeBuffer, NULL); //得到关于文件的信息

if(bQuery ==false)

{

InternetCloseHandle(hINet);

cout << "error query info" << endl;

return 3;

}

int FileSize=atol(szSizeBuffer); //atol函数把字符串转换成长整型数

string revData;

revData.resize(FileSize);

DWORD dwBytesRead;

BOOL bRead = InternetReadFile(hHttpFile, &revData[0], FileSize, &dwBytesRead); //该函数将循环读取数据块。

if(!bRead)

{

cout << "error to read file" << endl;

return 4;

}

ofstream out_file("duhui.txt");

out_file << revData; //输出到文件

InternetCloseHandle(hHttpFile); //关闭句柄

InternetCloseHandle(hINet);

cout << "抓取成功!/n" << endl;

system("pause");

return 0;

}

转载于:https://www.cnblogs.com/zhongbin/p/3178546.html

全部评论 (0)

还没有任何评论哟~