将HTML源读取到字符串

Kyl*_*yle 4 c++ get http

我希望你不要对我太过皱眉,但这应该很容易被一个人负责.我想将网站上的文件读成字符串,因此我可以从中提取信息.

我只想要一种简单的方法将HTML源代码读入字符串.环顾四个小时后,我看到了所有这些库和卷曲的东西.我只需要原始的HTML数据.我甚至不需要一个明确的答案.只是能帮助我改进搜索的东西.

为了清楚我想要一个我可以操作的字符串中的原始代码,不需要任何解析等.

小智 8

您需要一个HTTP客户端库,其中一个是libcurl.然后,您将向GETURL 发出请求并阅读响应,以便您选择的库如何提供它.

这是一个让你入门的例子,它是C所以我相信你可以解决它.

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
    res = curl_easy_perform(curl);

    /* always cleanup */ 
    curl_easy_cleanup(curl);
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是你标记了这个C++,所以如果你想要一个libcurl的C++包装器,那么就使用curlpp

#include <curlpp/curlpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>

using namespace curlpp::options;

int main(int, char **)
{
  try
  {
    // That's all that is needed to do cleanup of used resources
    curlpp::Cleanup myCleanup;

    // Our request to be sent.
    curlpp::Easy myRequest;

    // Set the URL.
    myRequest.setOpt<Url>("http://example.com");

    // Send request and get a result.
    // By default the result goes to standard output.
    myRequest.perform();
  }

  catch(curlpp::RuntimeError & e)
  {
    std::cout << e.what() << std::endl;
  }

  catch(curlpp::LogicError & e)
  {
    std::cout << e.what() << std::endl;
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)