C++ 可以用于编写爬虫,尽管相对于 Python 等其他语言,使用 C++ 编写爬虫可能会更加复杂和繁琐。以下是一个简单的 C++ 爬虫示例,它使用 libcurl 库来发送 HTTP 请求并解析响应。

#include <iostream>  
#include <string>  
#include <curl/curl.h>  
  
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {  
    ((std::string*)userp)->append((char*)contents, size * nmemb);  
    return size * nmemb;  
}  
  
int main(void) {  
    CURL* curl;  
    CURLcode res;  
    std::string readBuffer;  
  
    curl = curl_easy_init();  
    if(curl) {  
        curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");  
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);  
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);  
        res = curl_easy_perform(curl);  
        if(res != CURLE_OK) {  
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;  
        }  
        else {  
            std::cout << readBuffer << std::endl;  
        }  
        curl_easy_cleanup(curl);  
    }  
    return 0;  
}

这个示例程序使用 libcurl 库来发送一个 HTTP GET 请求到 "http://example.com",并将响应保存到 readBuffer 字符串中。WriteCallback 函数是一个回调函数,它会在接收到响应时被调用,并将接收到的数据追加到 readBuffer 中。

需要注意的是,C++ 爬虫通常需要更多的手动编码工作,包括处理 HTTP 请求和响应、解析 HTML 文档、处理异常和错误等。此外,C++ 相对于其他语言来说,社区和生态系统较小,可能需要更多的手动安装和配置依赖项。因此,如果你只是想快速编写一个爬虫程序,使用 Python 等其他语言可能会更加简单和方便。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐