C++抓網頁/獲取網頁內容


#include<windows.h>

#include<Wininet.h>

#include<iostream>

#include<fstream>

#include<string>

#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);     //web瀏覽器將在InternetReadFile上循環 ,不停地從Internet上讀入數據塊。

 

    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;

 

}


免責聲明!

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



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