python模組PycURL執行個體講解

來源:互聯網
上載者:User

在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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.