在Linux上有個常用的命令 curl(非常好用),支援curl的就是大名鼎鼎的libcurl庫;libcurl是功能強大的,而且是非常高效的函數庫。libcurl除了提供本身的C API之外,還有多達40種程式設計語言的Binding,這裡介紹的PycURL就是libcurl的Python binding。
在Python中對網頁進行GET/POST等請求,當需要考慮高效能的時候,libcurl是非常不錯的選擇,一般來說會比liburl、liburl2快不少,可能也會比Requests的效率更高。特別是使用PycURL的多並發請求時,更是效率很高的。個人感覺,其唯一的缺點是,由於是直接調用的是libcurl C庫,PycURL的函數介面之類的還和C中的東西很像,可能不是那麼的Pythonic,寫代碼的學習曲線稍微比liburl高一點兒。
還是看個簡單的例子吧:
| 代碼如下 |
複製代碼 |
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Dec 15, 2013 @author: Jay ''' import sys import pycurl import time class Test: def __init__(self): self.contents = '' def body_callback(self, buf): self.contents = self.contents + buf sys.stderr.write("Testing %sn" % pycurl.version) start_time = time.time() url = 'http://www.dianping.com/shanghai' t = Test() c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.WRITEFUNCTION, t.body_callback) c.perform() end_time = time.time() duration = end_time - start_time print c.getinfo(pycurl.HTTP_CODE), c.getinfo(pycurl.EFFECTIVE_URL) c.close() print 'pycurl takes %s seconds to get %s ' % (duration, url) print 'lenth of the content is %d' % len(t.contents) #print(t.contents) |
參考資料:
pycurl首頁: http://pycurl.sourceforge.net/
pycurl API: http://pycurl.sourceforge.net/doc/pycurl.html
一個並發處理的例子: https://github.com/pycurl/pycurl/blob/master/examples/retriever-multi.py
libcurl C API: http://curl.haxx.se/libcurl/c/