Python pycurl使用


pycurl的學習

  (2013-09-26 10:40:31)
  分類: python

 pycurl的使用

pycurl是curl的一個python版本。

 

pycurl的使用說明:

pycurl的使用主要是一些參數的設定。

1,c.setopt(pycurl.URL,myurl)

設定鏈接的地址

2,c.setopt(pycurl.HTTPHEADER,['Content-Type: application/json','Content-Length: '+str(len(remove_str))])

設置http的包頭信息。注意,長度的字符傳是用於put或者post等方法傳參數的。

3,c.setopt(pycurl.CUSTOMREQUEST,"DELETE")

設置封裝方法,有put,post,get,delete等多種方法

4, c.setopt(pycurl.POSTFIELDS,remove_str)

設置psot過去的數據,注意是一個字典樣式的字符串

5,c.setopt(pycurl.WRITEFUNCTION,b.write)

c.setopt(pycurl.FOLLOWLOCATION, 1)

設置寫的回調,所有輸出都定向到b.write中。

6,c.setopt(pycurl.MAXDEDIRS,5)

設置重定向次數

7,c.setopt(pycurl.CONNECTTIMEOUT,60)

c.setopt(pycurl.TIMEOUT,600)

設置鏈接超時,設置下載超時

8,c.setopt(pycurl.USERAGENT,"xxxx")

設置代理瀏覽器

9,c.setopt(pycurl.HEADER,1)

   開啟包頭輸出

    c.setopt(pycurl.HEADERFUNCTION,header_str.write)

將包頭輸出到header_str.write流中

10,c.perform()

執行curl命令

11,print b.getvalue()打印消息

12,print c.getinfo(c.HTTP_CODE)   //答應返回值

Print c.getinfo(c.CONTENT_TYPE)  //打印文本類型

Print c.getinfo(c.EFFECTIVE_URL)  //打印重定向URL

具體舉例:

環境:限制需要訪問地址

www.test.com/abc?afgf=afd

具體代碼如下:

 

 

  1.  Import  pycurl 
  2. Import StringIO 
  3.   
  4. checkurl="www.test.com/abc?afgf=afd 
  5. b=StringIO.StringIO() 
  6. c=pycurl.Curl() 
  7. c.setopt(pycurl.URL, checkurl) 
  8. c.setopt(pycurl.HTTPHEADER, ["Accept:"]) 
  9. c.setopt(pycurl.WRITEFUNCTION, b.write) 
  10. c.setopt(pycurl.FOLLOWLOCATION, 1) 
  11. c.setopt(pycurl.MAXREDIRS, 5) 
  12. c.perform() 
  13. Print b.getvalue() 
  14. Print c.getinfo(c.HTTP_CODE) 
  15. b.close() 
  16. c.close() 

傳參數的例子

 

  1. b = StringIO.StringIO() 
  2. c = pycurl.Curl() 
  3. mkdir_str = '[{"op":"MKDIRS","permission"=permission}]' 
  4. mkdir_url="http://192.168.0.112/abdf?op=MKDIRS&permission=%s" % (self.url_path,path,permission) 
  5. c.setopt(pycurl.URL, mkdir_url) 
  6. c.setopt(pycurl.HTTPHEADER,['Content-Type:application/json','Content-Length: '+str(len(mkdir_str))]) 
  7. c.setopt(pycurl.CUSTOMREQUEST,"PUT") 
  8. c.setopt(pycurl.POSTFIELDS,mkdir_str) 
  9.           
  10. c.setopt(pycurl.WRITEFUNCTION, b.write) 
  11. c.setopt(pycurl.FOLLOWLOCATION, 1) 
  12. c.setopt(pycurl.MAXREDIRS, 5) 
  13. c.perform() 
  14. status = c.getinfo(c.HTTP_CODE) 
  15. bbody = b.getvalue() 
  16. b.close() 

 

本文出自 “一直奔跑在路上” 博客,請務必保留此出處http://liran728729.blog.51cto.com/2505117/1151734


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM