我如何将从curl获得的html保存到txt文件中

问题描述 投票:0回答:1

我正在尝试使用c ++来从网站上抓取数据,我发现它是libcurl。我正在尝试保存curl从网站检索的HTML代码并将其保存到txt文件中,以便我可以从文件中解析HTML并检索所需的数据。

我的问题是如何将HTML保存到文件中?我下面的代码似乎没有将HTML代码保存到txt文件中,因为每当我运行代码时,txt文件仅包含数字0。

#define CURL_STATICLIB
#include <iostream>
#include <fstream>
#include "curl.h"
#include <string>

using namespace std;

int main(void)
{
    ofstream myfile;
    myfile.open("txt file location");

    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "website");
        /* example.com is redirected, so we tell libcurl to follow redirection */
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        myfile << res << endl;
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        /* always cleanup */
        curl_easy_cleanup(curl);
    }

    myfile.close();
    return 0;
}

我正在尝试使用c ++来从网站上抓取数据,我发现它是libcurl。我正在尝试保存curl从网站检索到的HTML代码,并将其保存到txt文件中,以便我可以解析...

c++ libcurl
1个回答
0
投票

根据curl_easy_setopt documentation,您需要设置变量CURLOPT_WRITEDATA。现在让我们看一下此页面:CURLOPT_WRITEDATA。它告诉我们,您需要使用CURLOPT_WRITEFUNCTION定义回调函数,也可以直接使用FILE*。采取最新的选择,它给出:

© www.soinside.com 2019 - 2024. All rights reserved.