2012-02-11 61 views
1

我正在使用在控制檯上運行的Microsoft Visual Studio 2010和C++語言。如何在C++中獲取網頁的源代碼?

我想去一個網頁,然後得到該網頁的來源(我的意思是來源是:在Firefox中,當你右鍵單擊,然後「查看頁面源代碼」),並將其保存在我的電腦作爲文本文件,以便以後可以讀取保存的文件。你可以給我一個如何去C++網站的例子,然後將HTML源代碼保存到我的電腦中嗎?我將不勝感激任何幫助

如何安裝libcurl?

當我使用#include <curl/curl.h>它說錯誤:無法打開源文件「捲曲/ curl.h。」

+2

試試'libcurl'。 – 2012-02-11 23:33:08

+2

@LightnessRacesinOrbit不,但是當它抓取這個問題時它會被鬱悶:) – sehe 2012-02-11 23:36:10

+0

@sehe:對, – 2012-02-11 23:36:28

回答

0

低水平的方法:winsockets + HTTP協議。

更高層次的方法:庫捲曲,WinINet API等。

0

瞭解瞭解protocol layeringsoftware layering第一基本面!

之後,決定您想要開發的圖層。然後爲您的特定任務決定低級或高級API。

順便說一句:您的具體任務不是C++的典型任務,您可以輕鬆使用curl實用程序,例如:curl YOURURL > file.html。不需要重新發明輪子。

0

這是一個小程序,我提取&保存/寫在一個文本文件中的Facebook帳戶源代碼。您可以根據需要更改它(您可以將「http://www.facebook.com」更改爲「http://www.google.com/」)。還請記住將wininet.a(庫)鏈接到您的項目。希望它會有所幫助:)

#include <windows.h> 
#include <wininet.h> 
#include <iostream> 
#include <conio.h> 
#include <fstream.h> 
fstream fs_obj; 
using namespace std; 

int main(int argc, char *argv[]) 
{ 

    fs_obj.open("temp.txt",ios::out | ios::app); 
    HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 

    HINTERNET hConnection = InternetConnectA(hInternet, "www.facebook.com", 80, " "," ", INTERNET_SERVICE_HTTP, 0, 0); //enter url here 

    HINTERNET hData = HttpOpenRequestA(hConnection, "GET", "/", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0); 

    char buf[ 2048 ] ; 

    HttpSendRequestA(hData, NULL, 0, NULL, 0) ; 
    string total; 
    DWORD bytesRead = 0 ; 
    DWORD totalBytesRead = 0 ; 

    while(InternetReadFile(hData, buf, 2000, &bytesRead) && bytesRead != 0) 
    { 
    buf[ bytesRead ] = 0 ; // insert the null terminator. 
    total=total+buf; 
    printf("%d bytes read\n", bytesRead) ; 

    totalBytesRead += bytesRead ; 
    } 

    fs_obj<<total<<"\n--------------------end---------------------\n"; 
    fs_obj.close(); 
    printf("\n\n END -- %d bytes read\n", bytesRead) ; 
    printf("\n\n END -- %d TOTAL bytes read\n", totalBytesRead) ; 

    cout<<endl<<total<<endl; //it will save source code to (temp.txt) file 
    InternetCloseHandle(hData) ; 
    InternetCloseHandle(hConnection) ; 
    InternetCloseHandle(hInternet) ; 
    system("pause"); 
} 

用temp.html重命名temp.txt,用瀏覽器打開它,你會得到那個網頁。