zoukankan      html  css  js  c++  java
  • 利用cURL来获取网页信息Using cURL to get webpage content

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <sstream>
    #include <string>
    
    extern "C" {
    #include <stdio.h>
    //#include <curl/easy.h>
    #include <curl/curl.h>
    }
    
    using namespace std;
    
    int writer(char* data, size_t size, size_t nmemb, string *buffer) {
            fprintf(stderr, "Hello, I am a function pointer\n");
    
            int result = 0;
            if (buffer != NULL) {
                    buffer->append(data, size * nmemb);
                    result = size * nmemb;
            }
    
            return result;
    }
    
    int main(int argc, char** args) {
            CURL* curl; // That is the connection, see : curl_easy_init
            CURLcode res; // Not needed, see : curl_easy_cleanup
    
            string buffer; // see: CURLOPT_WRITEDATA
    
            curl = curl_easy_init(); // Initilize web query
    
            if (curl) {
                    // set options for web query
                    curl_easy_setopt(curl, CURLOPT_URL, args[1]);
                    curl_easy_setopt(curl, CURLOPT_HEADER, 0); // No we don't need the header of the web content, Set to 0 and 
                                                                                                            // curl ignores the first line
                    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);//Don't follow anything else than the particular url requested
                    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); // Function Pointer 'writer' manages the required buffer size
                    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); // Data Pointer &buffer stores downloaded web content
            } else {
                    fprintf(stderr, "Error 1\n");
                    return 0;
            }
    
            res = curl_easy_perform(curl);
            //string s = (res);
            cout << res << endl;
            curl_easy_cleanup(curl);
    
            std::istringstream iss(buffer);
            string line, item;
    
            int linenum = 0;
    
            while (getline(iss, line)) {
                    linenum ++;
                    cout << "\nline #" << linenum << " : " << endl;
                    std::istringstream linestream(line);
    
                    int itemnum = 0;
    
                    while (getline(linestream, item, ',')) {
                            itemnum ++;
                            cout << "Item # " << itemnum << " : " << item << endl;
                    }
            }
    
            return 0;
    }

  • 相关阅读:
    基础抽象代数
    斜堆
    WC2018
    WC2019
    有向图上不相交路径计数
    生成树计数
    Pr&#252;fer序列
    反演
    1.1 Linux中的进程 --fork、孤儿进程、僵尸进程、文件共享分析
    Python程序的执行过程 解释型语言和编译型语言
  • 原文地址:https://www.cnblogs.com/java20130722/p/3206800.html
Copyright © 2011-2022 走看看