开源项目(库)之libcurl学习(一)

最近抽了点时间,将之前开发中使用到的一些开源库进行了下总结,主要是为了回顾一下自己所使用的一些库基础知识,并且加深理解,在这些库中,首先一个库就是libcurl,这个库很强大,当时在做openstack swift API时使用到了,这个库一个轻量级的HTTP编程库,里面封装了一套基于HTTP的上层应用协议的数据包的基本操作,其支持FTP,FTPS,TFTP,HTTP,HTTPS,GOPHER,TELNET,DICT,FILE和LDAP,跨平台,支持Windows,Unix,Linux等,线程安全,支持Ipv6。并且易于使用。下面就从安装开始,之前的开发是在Windows下开发的,现在的工作环境换为了Linux,但是不要紧,安装过程差不多,步骤如下:

1)下载libcurl文件,下载指令:sudo wget http://curl.haxx.se/download/curl-7.35.0.tar.gz

2)使用指令解压文件:tar -zxvf curl-7.35.0.tar.gz

3)./configure --prefix=/usr/local/libcurl
4)make

5)make install

经过上面几个步骤,libcurl库基本上就安装好了,下面我们就稍微写过小测试程序来测试测试,代码如下:

#ifndef __HTTP_CURL__H
#define __HTTP_CURL__H

#include <boost/smart_ptr.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp>
#include <boost/typeof/typeof.hpp>
#include <curl/curl.h>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
using namespace boost;
using namespace boost::xpressive;
#define MAX_BUFFERSIZE 1024*10
class HttpCurl
{
    public:
        HttpCurl()
        {
            conn = NULL;
            memset(errBuffer,0,sizeof(errBuffer));
        }
        ~HttpCurl()
        {
            curl_easy_cleanup(conn);
        }
        bool HttpCurlInit(string& context)
        {
            CURLcode code;
            string error;

            code = curl_global_init(CURL_GLOBAL_DEFAULT);
            if(CURLE_OK != code)
            {
                printf("Failed to global init default\n");
                return false;
            }

            conn = curl_easy_init();
            if(NULL == conn)
            {
                printf("Failed to create CURL\n");
                return false;
            }

            code = curl_easy_setopt(conn,CURLOPT_ERRORBUFFER,error.c_str());
            if(CURLE_OK != code)
            {
                printf("Failed to set error buffer\n");
                return false;
            }

            code = curl_easy_setopt(conn,CURLOPT_WRITEFUNCTION,HttpCurl::write);
            if(CURLE_OK != code)
            {
                printf("Failed to set write\n");
                return false;
            }
            code = curl_easy_setopt(conn,CURLOPT_WRITEDATA,&context);
            if(CURLE_OK != code)
            {
                printf("Failed to set write data\n");
                return false;
            }
            return true;
        }
        bool setUrl(string& url)
        {
            CURLcode code;
            code = curl_easy_setopt(conn,CURLOPT_URL,url.c_str());
            if(CURLE_OK != code)
            {
                printf("Failed to set URL\n");
                return false;
            }
            return true;
        }

        bool getHttpResponse()
        {
            CURLcode code;
            std::string error;
            code = curl_easy_perform(conn);
            if(CURLE_OK != code)
            {
                printf("Failed to get [%s]",error.c_str());
                return false;
            }
            return true;
        }

        static long write(void* data,int size,int nmemb,std::string& context)
        {
            long sizes = size*nmemb;
            std::string temp((char*)data,sizes);
            context += temp;
            return sizes;
        }

        bool save(const string& context,std::string filename)
        {
            CURLcode code;
            int retcode = 0;
            code = curl_easy_getinfo(conn,CURLINFO_RESPONSE_CODE,&retcode);
            if((CURLE_OK == code)&& retcode ==200)
            {
                int length = strlen(context.c_str());
                FILE* file = fopen(filename.c_str(),"w+");
                fseek(file,0,SEEK_SET);
                fwrite(context.c_str(),1,length,file);
                fclose(file);
                return  true;
            }
            return false;
        }
    private:
        CURL* conn;
        char errBuffer[MAX_BUFFERSIZE];
};


测试程序代码如下:

int main()
{
    string context;
    HttpCurl curl;
    curl.HttpCurlInit(context);
    curl.setUrl("www.renren.com");
    curl.getHttpResponse();
    curl.save(context,"text.txt");
    return 0;
}

通过简单的测试用例,可以看出libcurl使用的一些基本流程,接下来我们再看看一个使用libcurl写成的单线程爬虫程序,这个程序实现思路很简单,有机会将其改成多线程,代码如下:

class Spider
{
    public:
        Spider(shared_ptr<HttpCurl>& cul):httpCurl(cul)
        {
            urlSet.clear();
            finishUrlSet.clear();
        }
        ~Spider(){}

        bool init(std::string& context)
        {
            return httpCurl->HttpCurlInit(context);
        }

        void parseUrl(const string& context)
        {
            const string tag = "href";
            const string tag2 = "\"";
            string::size_type tempBegin,tempEnd,iter;
            tempBegin = tempEnd = 0;
            iter= context.find(tag);
            while(iter != string::npos)
            {
                tempBegin = context.find(tag2,iter);
                if(tempBegin != string::npos)
                {
                    ++tempBegin;
                    tempEnd = context.find(tag2,tempBegin);
                }
                if(tempEnd != string::npos && tempEnd > tempBegin)
                {
                    string url;
                    url.assign(context,tempBegin,(tempEnd-tempBegin));
                    urlSet.insert(url);
                }
                iter = context.find(tag,tempEnd);
            }
        }
        void filterUrl()
        {
            string tag = "http";
            urlSet_Iter iter = urlSet.begin();
            for(;iter != urlSet.end();)
            {
                string::size_type index = (*iter).find(tag);
                if(index == string::npos)
                    urlSet.erase(iter);
                iter++;
            }
        }

        bool write(const string& context,const string& filename)
        {
            return httpCurl->save(context,filename);
        }

        void start(std::string url,std::string& context)
        {
            httpCurl->setUrl(url);
            httpCurl->getHttpResponse();
            parseUrl(context);
            filterUrl();
        }

        void displayUrl()
        {
            urlSet_Iter iter = urlSet.begin();
            for(; iter != urlSet.end();++iter)
            {
                cout<<*iter<<endl;
            }
        }
        void loop(const std::string& url,std::string& context)
        {
            start(url,context);
            for(urlSet_Iter iter = urlSet.begin();iter != urlSet.end();++iter)
            {
                if(finishUrlSet.find(*iter) != finishUrlSet.end())
                    continue;
                printf("%s\n",(*iter).c_str());
                char filename[64];
                memset(filename,0,sizeof(filename));
                sprintf(filename,"%d.html",fileIndex++);
                context.clear();
                start(*iter,context);
                write(context,filename);
                finishUrlSet.insert(*iter);
            }
        }
    private:
        shared_ptr<HttpCurl> httpCurl;
        std::set<string> urlSet;
        std::set<string> finishUrlSet;
        typedef std::set<string>::iterator urlSet_Iter;

};

测试程序:

#include "curlTest.h"

int main()
{
    string context;
    shared_ptr<HttpCurl> curl(new HttpCurl());
    Spider spider(curl);

    spider.init(context);
    spider.loop("www.renren.com",context);
    return 0;
}

测试结果:

http://a.xnimg.cn/favicon-rr.ico?ver=3
http://a.xnimg.cn/n/core/res/certificate.jpg
http://a.xnimg.cn/wap/apple_icon_.png
http://app.renren.com
http://app.renren.com/?origin=40206
http://app.renren.com/activity/specialpage?activity=girlgame&origin=40240
http://app.renren.com/activity/specialpage?activity=newgame&origin=40238
http://app.renren.com/activity/specialpage?activity=sanguo&origin=40239
http://app.renren.com/list?category=10&type=1&origin=40060&menu=1
http://app.renren.com/list?category=10&type=1&origin=40065&menu=1
http://app.renren.com/list?category=10&type=1&origin=40207&menu=1
http://app.renren.com/list?category=11&type=1
http://app.renren.com/list?category=11&type=1&origin=3142&added=0
http://app.renren.com/list?category=11&type=1&origin=40131
http://app.renren.com/list?category=11&type=1&origin=40132
http://app.renren.com/list?category=11&type=1&origin=40189
http://app.renren.com/list?category=11&type=1&origin=50298
http://app.renren.com/list?category=12&type=1&origin=3142&added=0
http://app.renren.com/list?category=12&type=1&origin=40131
http://app.renren.com/list?category=12&type=1&origin=40132
http://app.renren.com/list?category=13&type=1
http://app.renren.com/list?category=13&type=1&origin=3142&added=0
http://app.renren.com/list?category=13&type=1&origin=40131
http://app.renren.com/list?category=13&type=1&origin=40132
http://app.renren.com/list?category=13&type=1&origin=40188
http://app.renren.com/list?category=13&type=1&origin=40189
http://app.renren.com/list?category=13&type=1&origin=50298
http://app.renren.com/list?category=14&type=1
http://app.renren.com/list?category=14&type=1&origin=3113
http://app.renren.com/list?category=14&type=1&origin=3142&added=0
http://app.renren.com/list?category=14&type=1&origin=40188
http://app.renren.com/list?category=14&type=1&origin=50298
http://app.renren.com/list?category=15&type=1&origin=3142&added=0
http://app.renren.com/list?category=15&type=1&origin=40131
http://app.renren.com/list?category=17&type=1&origin=3142&added=0
http://app.renren.com/list?category=19&type=1
http://app.renren.com/list?category=19&type=1&origin=3113
http://app.renren.com/list?category=19&type=1&origin=3142&added=0
http://app.renren.com/list?category=19&type=1&origin=40132
http://app.renren.com/list?category=19&type=1&origin=40188
http://app.renren.com/list?category=19&type=1&origin=50298
http://app.renren.com/list?category=20&type=1&origin=40066&menu=2
http://app.renren.com/list?category=20&type=1&origin=40210&menu=2
^C
总结

      本篇博文主要是安装了下libcurl,并且在此基础上实现了一个简单的爬虫程序,代码结构很简单,至于libcurl的一些接口介绍什么的,大家可以去其官网上看,在这里就略过了,在写这个爬虫程序时,一开始一心想用boost里的regex做正则表达式匹配url,但是中间遇到了问题,所以临时自己写了个提取url的parseURL,另外这个爬虫程序使用的是单线程的,有机会的话,我会将其改成支持多线程,其实很多东西在于自己去实践,才能体会到其中的奥秘,好了,这篇博文到此就结束了,多谢。

如果需要,请注明转载,多谢

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值