Sản phẩmTích hợpTài nguyênTài liệuGiá cả
Bắt đầu ngay

© 2026 CapSolver. All rights reserved.

Liên hệ chúng tôi

Slack: lola@capsolver.com

Sản phẩm

  • reCAPTCHA v2
  • reCAPTCHA v3
  • Cloudflare Turnstile
  • Cloudflare Challenge
  • AWS WAF
  • Tiện ích trình duyệt
  • Thêm nhiều loại CAPTCHA

Tích hợp

  • Selenium
  • Playwright
  • Puppeteer
  • n8n
  • Đối tác
  • Xem tất cả tích hợp

Tài nguyên

  • Chương trình giới thiệu
  • Tài liệu
  • Tham chiếu API
  • Blog
  • Câu hỏi thường gặp
  • Thuật ngữ
  • Trạng thái

Pháp lý

  • Điều khoản dịch vụ
  • Chính sách bảo mật
  • Chính sách hoàn tiền
  • Không bán thông tin cá nhân của tôi
Blog/All/Cách sử dụng libcurl để WebScraping
Oct21, 2024

Cách sử dụng libcurl để WebScraping

Anh Tuan

Anh Tuan

Data Science Expert

Web scraping là một kỹ thuật mạnh mẽ để trích xuất dữ liệu từ các trang web, cho phép tự động hóa các tác vụ như thu thập thông tin giá cả, theo dõi cập nhật nội dung hoặc thu thập các tập dữ liệu lớn. Một trong những thư viện phổ biến nhất để thực hiện web scraping trong C++ là libcurl, một thư viện truyền tải URL phía máy khách miễn phí và mã nguồn mở. Nó hỗ trợ nhiều giao thức như HTTP, HTTPS, FTP, và nhiều hơn nữa, làm cho nó trở thành lựa chọn lý tưởng để truy xuất nội dung web.

Giới thiệu về libcurl

libcurl là một thư viện C mạnh mẽ để thực hiện các yêu cầu HTTP, hỗ trợ nhiều giao thức như HTTP, HTTPS, FTP và nhiều giao thức khác. Nó là một công cụ linh hoạt được sử dụng rộng rãi trong các ứng dụng C++ để thực hiện các yêu cầu web.

Tính năng:

  • Hỗ trợ đa giao thức: HTTP, HTTPS, FTP, FTPS, SMTP, và nhiều giao thức khác.
  • Hỗ trợ bất đồng: Thông qua CURLM để quản lý nhiều yêu cầu cùng lúc.
  • Xử lý lỗi: Cung cấp thông báo lỗi chi tiết và mã trạng thái.
  • Xác thực: Hỗ trợ xác thực cơ bản, tiêu hóa, NTLM, đàm phán, v.v.
  • Cookie và phiên: Có thể quản lý cookie và thông tin phiên một cách dễ dàng.

Điều kiện tiên quyết

Trước khi sử dụng libcurl, bạn phải:

  • Cài đặt libcurl trên hệ thống của bạn.
  • Bao gồm tiêu đề curl/curl.h trong mã C++ của bạn.

Bạn có thể cài đặt libcurl trên Linux bằng:

bash Copy
sudo apt-get install libcurl4-openssl-dev

Ví dụ cơ bản: Thực hiện yêu cầu GET

Dưới đây là cách thực hiện yêu cầu GET đơn giản bằng libcurl trong C++:

cpp Copy
#include <iostream>
#include <curl/curl.h>

static 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() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/get");
        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 << "Response: " << readBuffer << std::endl;
        }

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return 0;
}

Ví dụ về web scraping: Lấy dữ liệu JSON từ API

Đây là một ví dụ về việc chúng ta lấy dữ liệu từ API và in kết quả:

cpp Copy
#include <iostream>
#include <curl/curl.h>

static 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() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts");
        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 << "Response: " << readBuffer << std::endl;
        }

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return 0;
}

Xử lý Proxy với libcurl

Để định tuyến yêu cầu của bạn thông qua máy chủ proxy bằng libcurl:

cpp Copy
#include <iostream>
#include <curl/curl.h>

static 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() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/ip");
        curl_easy_setopt(curl, CURLOPT_PROXY, "http://proxyserver:8080");
        curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, "username:password");
        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 << "Response: " << readBuffer << std::endl;
        }

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return 0;
}

Xử lý Cookie với libcurl

libcurl có thể quản lý cookie bằng cách bật tùy chọn COOKIEFILE:

cpp Copy
#include <iostream>
#include <curl/curl.h>

static 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() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/cookies/set?name=value");
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
        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 << "Response: " << readBuffer << std::endl;
        }

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return 0;
}

Sử dụng nâng cao: Tiêu đề tùy chỉnh và yêu cầu POST

Để gửi tiêu đề tùy chỉnh hoặc thực hiện yêu cầu POST bằng libcurl:

cpp Copy
#include <iostream>
#include <curl/curl.h>

static 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() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;
    
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if(curl) {
        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "User-Agent: Mozilla/5.0");
        headers = curl_slist_append(headers, "Accept-Language: en-US,en;q=0.5");

        curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/post");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=testuser&password=testpass");
        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 << "Response: " << readBuffer << std::endl;
        }

        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();

    return 0;
}

Ví dụ: Giải quyết ReCaptcha V3 bằng CapSolver và libcurl (C++)

Trong ví dụ này, chúng ta sẽ trình bày cách giải quyết ReCaptcha V3 bằng CapSolver: với thư viện libcurl trong C++. API CapSolver cho phép tương tác dễ dàng với các tác vụ ReCaptcha và truy xuất các giải pháp.

Trước khi bắt đầu, hãy đảm bảo rằng bạn có các điều kiện tiên quyết sau:

  • libcurl được cài đặt trên hệ thống của bạn (cài đặt nó thông qua sudo apt-get install libcurl4-openssl-dev trên Linux).
  • Một khóa API CapSolver (thay thế "YourKey" trong mã dưới đây bằng khóa thực tế của bạn).

Dưới đây là hướng dẫn từng bước để giải quyết ReCaptcha V3 bằng CapSolver:

Bước 1: Tạo tác vụ

Bước đầu tiên là gửi yêu cầu đến API của CapSolver để tạo tác vụ giải quyết ReCaptcha. Tác vụ bao gồm các chi tiết như URL trang web, khóa trang (từ trang đích) và hành động trang cụ thể.

cpp Copy
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <json/json.h>

const std::string CAPSOLVER_KEY = "YourKey";
const std::string PAGE_URL = "https://antcpt.com/score_detector";
const std::string PAGE_KEY = "6LcR_okUAAAAAPYrPe-HK_0RULO1aZM15ENyM-Mf";
const std::string PAGE_ACTION = "homepage";

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

std::string createTask(const std::string& url, const std::string& key, const std::string& action) {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.capsolver.com/createTask");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

        // JSON payload để tạo tác vụ
        Json::Value payload;
        payload["clientKey"] = CAPSOLVER_KEY;
        payload["task"]["type"] = "ReCaptchaV3TaskProxyLess";
        payload["task"]["websiteURL"] = url;
        payload["task"]["websiteKey"] = key;
        payload["task"]["pageAction"] = action;

        Json::StreamWriterBuilder writer;
        std::string requestData = Json::writeString(writer, payload);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestData.c_str());

        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        res = curl_easy_perform(curl);
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }
    return readBuffer;
}

Hàm này gửi yêu cầu POST đến API của CapSolver với các chi tiết tác vụ cần thiết và trả về phản hồi, trong đó sẽ bao gồm taskId.

Bước 2: Truy xuất giải pháp CAPTCHA

Sau khi tác vụ được tạo, bạn sẽ cần truy vấn API của CapSolver để lấy kết quả của tác vụ, trong đó chứa token để bỏ qua thử thách ReCaptcha.

cpp Copy
std::string getTaskResult(const std::string& taskId) {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.capsolver.com/getTaskResult");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

        // JSON payload để lấy kết quả tác vụ
        Json::Value payload;
        payload["clientKey"] = CAPSOLVER_KEY;
        payload["taskId"] = taskId;

        Json::StreamWriterBuilder writer;
        std::string requestData = Json::writeString(writer, payload);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestData.c_str());

        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        do {
            readBuffer.clear();
            res = curl_easy_perform(curl);
            std::this_thread::sleep_for(std::chrono::seconds(5));
        } while (readBuffer.find("\"status\":\"ready\"") == std::string::npos);

        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }
    return readBuffer;
}

Hàm này liên tục kiểm tra trạng thái của tác vụ cho đến khi nó sẵn sàng, tại thời điểm đó nó sẽ trả về giải pháp ReCaptcha.

Bước 3: Ghép các phần lại với nhau

Cuối cùng, đây là cách bạn có thể tích hợp cả hai hàm vào mã chính của bạn:

cpp Copy
int main() {
    std::cout << "Creating CAPTCHA task..." << std::endl;
    std::string taskResponse = createTask(PAGE_URL, PAGE_KEY, PAGE_ACTION);

    Json::CharReaderBuilder reader;
    Json::Value jsonResponse;
    std::string errors;
    std::istringstream taskStream(taskResponse);
    std::string taskId;

    if (Json::parseFromStream(reader, taskStream, &jsonResponse, &errors)) {
        taskId = jsonResponse["taskId"].asString();
        std::cout << "Task ID: " << taskId << std::endl;

        std::cout << "Retrieving CAPTCHA result..." << std::endl;
        std::string resultResponse = getTaskResult(taskId);

        Json::Value resultJson;
        std::istringstream resultStream(resultResponse);
        Json::parseFromStream(reader, resultStream, &resultJson, &errors);

        std::string token = resultJson["solution"]["gRecaptchaResponse"].asString();
        std::cout << "Token Solution: " << token << std::endl;
    } else {
        std::cerr << "Error parsing task response: " << errors << std::endl;
    }

    return 0;
}

Mã này sẽ:

  1. Tạo một tác vụ ReCaptcha thông qua CapSolver.
  2. Chờ tác vụ hoàn thành.
  3. Truy xuất giải pháp token ReCaptcha và in ra.

Mã thưởng

Nhận Mã thưởng của bạn cho các giải pháp captcha hàng đầu tại CapSolver: scrape. Sau khi đổi mã, bạn sẽ nhận được thêm 5% tiền thưởng sau mỗi lần nạp tiền, không giới hạn lần.

CapSolver Bonus

Kết luận

Với libcurl, bạn có thể dễ dàng xử lý các yêu cầu HTTP trong các ứng dụng C++. Bằng cách tích hợp nó với CapSolver, bạn có thể giải quyết các captcha như ReCaptcha V3 và sử dụng kết quả trong các yêu cầu của bạn.

Xem thêm

n8nMar 09, 2026

Cách Giải reCAPTCHA v2/v3 Sử Dụng CapSolver và n8n

Xây dựng API giải eCAPTCHA v2/v3 bằng CapSolver và n8n. Tìm hiểu cách tự động hóa việc giải token, gửi token đến website và trích xuất dữ liệu được bảo vệ mà không cần lập trình.

Anh Tuan
Anh Tuan
Apr 22, 2026

Trí tuệ nhân tạo tốt nhất để giải các câu đố hình ảnh: Các công cụ và chiến lược hàng đầu cho năm 2026

Khám phá AI tốt nhất để giải các câu đố hình ảnh. Học cách Vision Engine và APIs ImageToText của CapSolver tự động hóa các thách thức thị giác phức tạp với độ chính xác cao.

Anh Tuan

Nội dung

Anh Tuan
web scrapingApr 22, 2026

Kiến trúc Trích xuất Dữ liệu Từ Web bằng Rust cho Trích xuất Dữ liệu Có Thể Mở Rộng

Học kiến trúc gỡ mã web Rust có thể mở rộng với reqwest, scraper, gỡ mã bất đồng bộ, gỡ mã trình duyệt không đầu, xoay proxy và xử lý CAPTCHA tuân thủ.

Anh Tuan
Anh Tuan
Apr 22, 2026

API Tìm kiếm so với Chuỗi cung ứng tri thức: Hướng dẫn cơ sở hạ tầng dữ liệu AI

Học cách các công cụ API tìm kiếm, chuỗi cung ứng kiến thức, quy trình API SERP và dòng dữ liệu AI định hình cơ sở hạ tầng dữ liệu web hiện đại cho AI.

Anh Tuan
Anh Tuan