2012-02-11 93 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,用浏览器打开它,你会得到那个网页。