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

http://blog.csdn.net/zmyer/article/details/19130217

最近抽了点时间,将之前开发中使用到的一些开源库进行了下总结,主要是为了回顾一下自己所使用的一些库基础知识,并且加深理解,在这些库中,首先一个库就是libcurl,这个库很强大,当时在做openstack swift API时使用到了,这个库一个轻量级的HTTP编程库,里面封装了一套基于HTTP的上层应用协议的数据包的基本操作,其支持FTPFTPSTFTPHTTPHTTPSGOPHERTELNETDICTFILELDAP,跨平台,支持WindowsUnixLinux等,线程安全,支持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库基本上就安装好了,下面我们就稍微写过小测试程序来测试测试,代码如下:

[cpp]  view plain  copy
  1. #ifndef __HTTP_CURL__H  
  2. #define __HTTP_CURL__H  
  3.   
  4. #include <boost/smart_ptr.hpp>  
  5. #include <boost/xpressive/xpressive_dynamic.hpp>  
  6. #include <boost/typeof/typeof.hpp>  
  7. #include <curl/curl.h>  
  8. #include <string>  
  9. #include <string.h>  
  10. #include <stdio.h>  
  11. #include <stdlib.h>  
  12. #include <unistd.h>  
  13. using namespace std;  
  14. using namespace boost;  
  15. using namespace boost::xpressive;  
  16. #define MAX_BUFFERSIZE 1024*10  
  17. class HttpCurl  
  18. {  
  19.     public:  
  20.         HttpCurl()  
  21.         {  
  22.             conn = NULL;  
  23.             memset(errBuffer,0,sizeof(errBuffer));  
  24.         }  
  25.         ~HttpCurl()  
  26.         {  
  27.             curl_easy_cleanup(conn);  
  28.         }  
  29.         bool HttpCurlInit(string& context)  
  30.         {  
  31.             CURLcode code;  
  32.             string error;  
  33.   
  34.             code = curl_global_init(CURL_GLOBAL_DEFAULT);  
  35.             if(CURLE_OK != code)  
  36.             {  
  37.                 printf("Failed to global init default\n");  
  38.                 return false;  
  39.             }  
  40.   
  41.             conn = curl_easy_init();  
  42.             if(NULL == conn)  
  43.             {  
  44.                 printf("Failed to create CURL\n");  
  45.                 return false;  
  46.             }  
  47.   
  48.             code = curl_easy_setopt(conn,CURLOPT_ERRORBUFFER,error.c_str());  
  49.             if(CURLE_OK != code)  
  50.             {  
  51.                 printf("Failed to set error buffer\n");  
  52.                 return false;  
  53.             }  
  54.   
  55.             code = curl_easy_setopt(conn,CURLOPT_WRITEFUNCTION,HttpCurl::write);  
  56.             if(CURLE_OK != code)  
  57.             {  
  58.                 printf("Failed to set write\n");  
  59.                 return false;  
  60.             }  
  61.             code = curl_easy_setopt(conn,CURLOPT_WRITEDATA,&context);  
  62.             if(CURLE_OK != code)  
  63.             {  
  64.                 printf("Failed to set write data\n");  
  65.                 return false;  
  66.             }  
  67.             return true;  
  68.         }  
  69.         bool setUrl(string& url)  
  70.         {  
  71.             CURLcode code;  
  72.             code = curl_easy_setopt(conn,CURLOPT_URL,url.c_str());  
  73.             if(CURLE_OK != code)  
  74.             {  
  75.                 printf("Failed to set URL\n");  
  76.                 return false;  
  77.             }  
  78.             return true;  
  79.         }  
  80.   
  81.         bool getHttpResponse()  
  82.         {  
  83.             CURLcode code;  
  84.             std::string error;  
  85.             code = curl_easy_perform(conn);  
  86.             if(CURLE_OK != code)  
  87.             {  
  88.                 printf("Failed to get [%s]",error.c_str());  
  89.                 return false;  
  90.             }  
  91.             return true;  
  92.         }  
  93.   
  94.         static long write(void* data,int size,int nmemb,std::string& context)  
  95.         {  
  96.             long sizes = size*nmemb;  
  97.             std::string temp((char*)data,sizes);  
  98.             context += temp;  
  99.             return sizes;  
  100.         }  
  101.   
  102.         bool save(const string& context,std::string filename)  
  103.         {  
  104.             CURLcode code;  
  105.             int retcode = 0;  
  106.             code = curl_easy_getinfo(conn,CURLINFO_RESPONSE_CODE,&retcode);  
  107.             if((CURLE_OK == code)&& retcode ==200)  
  108.             {  
  109.                 int length = strlen(context.c_str());  
  110.                 FILE* file = fopen(filename.c_str(),"w+");  
  111.                 fseek(file,0,SEEK_SET);  
  112.                 fwrite(context.c_str(),1,length,file);  
  113.                 fclose(file);  
  114.                 return  true;  
  115.             }  
  116.             return false;  
  117.         }  
  118.     private:  
  119.         CURL* conn;  
  120.         char errBuffer[MAX_BUFFERSIZE];  
  121. };  


测试程序代码如下:

[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.     string context;  
  4.     HttpCurl curl;  
  5.     curl.HttpCurlInit(context);  
  6.     curl.setUrl("www.renren.com");  
  7.     curl.getHttpResponse();  
  8.     curl.save(context,"text.txt");  
  9.     return 0;  
  10. }  

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

[cpp]  view plain  copy
  1. class Spider  
  2. {  
  3.     public:  
  4.         Spider(shared_ptr<HttpCurl>& cul):httpCurl(cul)  
  5.         {  
  6.             urlSet.clear();  
  7.             finishUrlSet.clear();  
  8.         }  
  9.         ~Spider(){}  
  10.   
  11.         bool init(std::string& context)  
  12.         {  
  13.             return httpCurl->HttpCurlInit(context);  
  14.         }  
  15.   
  16.         void parseUrl(const string& context)  
  17.         {  
  18.             const string tag = "href";  
  19.             const string tag2 = "\"";  
  20.             string::size_type tempBegin,tempEnd,iter;  
  21.             tempBegin = tempEnd = 0;  
  22.             iter= context.find(tag);  
  23.             while(iter != string::npos)  
  24.             {  
  25.                 tempBegin = context.find(tag2,iter);  
  26.                 if(tempBegin != string::npos)  
  27.                 {  
  28.                     ++tempBegin;  
  29.                     tempEnd = context.find(tag2,tempBegin);  
  30.                 }  
  31.                 if(tempEnd != string::npos && tempEnd > tempBegin)  
  32.                 {  
  33.                     string url;  
  34.                     url.assign(context,tempBegin,(tempEnd-tempBegin));  
  35.                     urlSet.insert(url);  
  36.                 }  
  37.                 iter = context.find(tag,tempEnd);  
  38.             }  
  39.         }  
  40.         void filterUrl()  
  41.         {  
  42.             string tag = "http";  
  43.             urlSet_Iter iter = urlSet.begin();  
  44.             for(;iter != urlSet.end();)  
  45.             {  
  46.                 string::size_type index = (*iter).find(tag);  
  47.                 if(index == string::npos)  
  48.                     urlSet.erase(iter);  
  49.                 iter++;  
  50.             }  
  51.         }  
  52.   
  53.         bool write(const string& context,const string& filename)  
  54.         {  
  55.             return httpCurl->save(context,filename);  
  56.         }  
  57.   
  58.         void start(std::string url,std::string& context)  
  59.         {  
  60.             httpCurl->setUrl(url);  
  61.             httpCurl->getHttpResponse();  
  62.             parseUrl(context);  
  63.             filterUrl();  
  64.         }  
  65.   
  66.         void displayUrl()  
  67.         {  
  68.             urlSet_Iter iter = urlSet.begin();  
  69.             for(; iter != urlSet.end();++iter)  
  70.             {  
  71.                 cout<<*iter<<endl;  
  72.             }  
  73.         }  
  74.         void loop(const std::string& url,std::string& context)  
  75.         {  
  76.             start(url,context);  
  77.             for(urlSet_Iter iter = urlSet.begin();iter != urlSet.end();++iter)  
  78.             {  
  79.                 if(finishUrlSet.find(*iter) != finishUrlSet.end())  
  80.                     continue;  
  81.                 printf("%s\n",(*iter).c_str());  
  82.                 char filename[64];  
  83.                 memset(filename,0,sizeof(filename));  
  84.                 sprintf(filename,"%d.html",fileIndex++);  
  85.                 context.clear();  
  86.                 start(*iter,context);  
  87.                 write(context,filename);  
  88.                 finishUrlSet.insert(*iter);  
  89.             }  
  90.         }  
  91.     private:  
  92.         shared_ptr<HttpCurl> httpCurl;  
  93.         std::set<string> urlSet;  
  94.         std::set<string> finishUrlSet;  
  95.         typedef std::set<string>::iterator urlSet_Iter;  
  96.   
  97. };  

测试程序:

[cpp]  view plain  copy
  1. #include "curlTest.h"  
  2.   
  3. int main()  
  4. {  
  5.     string context;  
  6.     shared_ptr<HttpCurl> curl(new HttpCurl());  
  7.     Spider spider(curl);  
  8.   
  9.     spider.init(context);  
  10.     spider.loop("www.renren.com",context);  
  11.     return 0;  
  12. }  

测试结果:

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,另外这个爬虫程序使用的是单线程的,有机会的话,我会将其改成支持多线程,其实很多东西在于自己去实践,才能体会到其中的奥秘,好了,这篇博文到此就结束了,多谢。





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值