使用c++语言写一个爬虫
以下是一个使用C++语言编写的简单爬虫示例:
#include <iostream>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t totalSize = size * nmemb;
output->append((char*)contents, totalSize);
return totalSize;
}
int main() {
CURL* curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
std::string url = "http://example.com";
std::string output;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &output);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
std::cout << "Response: " << output << std::endl;
} else {
std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
该程序使用libcurl库进行网络请求,并将响应结果保存在一个字符串变量中。在这个示例中,我们使用curl_easy_setopt函数设置URL和回调函数,然后使用curl_easy_perform函数执行请求。最后,我们输出响应结果或错误信息。
请注意,此示例仅用于演示目的,并且可能需要根据实际需求进行修改和优化
原文地址: https://www.cveoy.top/t/topic/h6as 著作权归作者所有。请勿转载和采集!