Python PycURL 網路編程執行個體及自動處理Cookie詳解

來源:互聯網
上載者:User

Python PycURL 網路編程執行個體


在使用urllib的時候經常會死掉,以前debug過,是沒有設定 timing out 所以逾時後就會死掉。
PycURL是curl的python庫,雖然有些curl的功能沒有實現,但是還是很強勁的。

curl是非常強勁的一個工具,
google內部用它來 debug GDATA API. Using cURL to interact with Google data services

可以去 http://pycurl.sourceforge.net/ 下載最新的PycURL。


簡單的PycURL例子

import pycurlimport StringIO url = "http://www.google.com/"crl = pycurl.Curl()crl.setopt(pycurl.VERBOSE,1)crl.setopt(pycurl.FOLLOWLOCATION, 1)crl.setopt(pycurl.MAXREDIRS, 5)crl.fp = StringIO.StringIO()crl.setopt(pycurl.URL, url)crl.setopt(crl.WRITEFUNCTION, crl.fp.write)crl.perform()print crl.fp.getvalue()



PycURL 自動處理cookie

import pycurlimport StringIO url = "http://www.google.com/"crl = pycurl.Curl()crl.setopt(pycurl.VERBOSE,1)crl.setopt(pycurl.FOLLOWLOCATION, 1)crl.setopt(pycurl.MAXREDIRS, 5)crl.fp = StringIO.StringIO()crl.setopt(pycurl.URL, url)crl.setopt(crl.WRITEFUNCTION, crl.fp.write) # Option -b/--cookie  Cookie string or file to read cookies from# Note: must be a string, not a file object.crl.setopt(pycurl.COOKIEFILE, "cookie_file_name") # Option -c/--cookie-jar  Write cookies to this file after operation# Note: must be a string, not a file object.crl.setopt(pycurl.COOKIEJAR, "cookie_file_name") crl.perform()print crl.fp.getvalue()



PycURL 實現POST方法

import pycurlimport StringIOimport urllib url = "http://www.google.com/"post_data_dic = {"name":"value"}crl = pycurl.Curl()crl.setopt(pycurl.VERBOSE,1)crl.setopt(pycurl.FOLLOWLOCATION, 1)crl.setopt(pycurl.MAXREDIRS, 5)#crl.setopt(pycurl.AUTOREFERER,1) crl.setopt(pycurl.CONNECTTIMEOUT, 60)crl.setopt(pycurl.TIMEOUT, 300)#crl.setopt(pycurl.PROXY,proxy)crl.setopt(pycurl.HTTPPROXYTUNNEL,1)#crl.setopt(pycurl.NOSIGNAL, 1)crl.fp = StringIO.StringIO()crl.setopt(pycurl.USERAGENT, "dhgu hoho") # Option -d/--data    HTTP POST datacrl.setopt(crl.POSTFIELDS,  urllib.urlencode(post_data_dic)) crl.setopt(pycurl.URL, url)crl.setopt(crl.WRITEFUNCTION, crl.fp.write)crl.perform() print crl.fp.getvalue()



urllib 逾時設定

import socketsocket.setdefaulttimeout(5.0)




Python中Cookie的處理:自動處理Cookie,儲存為Cookie檔案,從檔案載入Cookie

Python中的Cookie相關的庫

Python中有內建的模組:cookielib

可以處理cookie相關的很多事情。

包括

    自動處理cookie:cookie資料是儲存在記憶體中
    自動處理cookie:支援Cookie資料存放到檔案中
        其中有兩種格式:
            LWP
            Mozilla
        進一步,再支援:
            將cookie存到檔案裡面
            從檔案中載入cookie

更多詳細格式和解釋,請直接看下面的代碼。

 
Python中自動處理Cookie,將Cookie儲存到檔案,從檔案中讀取Cookie

Python代碼:

#!/usr/bin/python# -*- coding: utf-8 -*-"""Version:    2013-01-15Author:     CrifanContact:    admin (at) crifan.com""" import os;import cookielib;import urllib2; def pythonAutoHandleCookie():    """        Demo how to auto handle cookie in Python            cookies in memory            cookies in file:                save cookie to file                    LWP     format                    Mozilla format                load cookie from file    """     print "1. Demo how to auto handle cookie (in memory)";    cookieJarInMemory = cookielib.CookieJar();    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarInMemory));    urllib2.install_opener(opener);    print "after init, cookieJarInMemory=",cookieJarInMemory; #after init, cookieJarInMemory=     #!!! following urllib2 will auto handle cookies    demoUrl = "http://www.google.com/";    response = urllib2.urlopen(demoUrl);    #here, we already got response cookies    print "after urllib2.urlopen, cookieJarInMemory=",cookieJarInMemory;    #after urllib2.urlopen, cookieJarInMemory= <cookielib.CookieJar[, , ]>              print "2. Demo how to auto handle cookie in file, LWP format";    cookieFilenameLWP = "localCookiesLWP.txt";    cookieJarFileLWP = cookielib.LWPCookieJar(cookieFilenameLWP);    #will create (and save to) new cookie file    cookieJarFileLWP.save();    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileLWP));    urllib2.install_opener(opener);    #!!! following urllib2 will auto handle cookies    demoUrl = "http://www.google.com/";    response = urllib2.urlopen(demoUrl);    #update cookies, save cookies into file    cookieJarFileLWP.save();    #for demo, print cookies in file    print "LWP cookies:";    print open(cookieFilenameLWP).read(os.path.getsize(cookieFilenameLWP));    # #LWP-Cookies-2.0    # Set-Cookie3: PREF="ID=34c1415b570a93ae:FF=0:NW=1:TM=1358236121:LM=1358236121:S=gEVVojW4x37ht5n-"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0    # Set-Cookie3: NID="67=JI_uEwUm5GDrQ_vCwAp2z_YGU7MdLm5CLMa4CNLF7RQuTDMzrrk1EjRddGcnpoFbht81LaV9spxZQQInf0mPS6lDrvcRqBBL5NOTmy8SwOzA6HWC3iTIo4-o3fO1Udkv"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2013-07-17 07:48:41Z"; HttpOnly=None; version=0    # Set-Cookie3: PREF="ID=8f7e4efca89bdb1b:U=f85a4afa4db021aa:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=2WR59hDWutdnUJtF"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2015-01-15 07:48:41Z"; version=0     print "3. Demo how to auto handle cookie in file, Mozilla Format";    cookieFilenameMozilla = "localCookiesMozilla.txt";    cookieJarFileMozilla = cookielib.MozillaCookieJar(cookieFilenameMozilla);    #will create (and save to) new cookie file    cookieJarFileMozilla.save();    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJarFileMozilla));    urllib2.install_opener(opener);    #!!! following urllib2 will auto handle cookies    demoUrl = "http://www.google.com/";    response = urllib2.urlopen(demoUrl);    #update cookies, save cookies into file    cookieJarFileMozilla.save();    #for demo, print cookies in file    print "Mozilla cookies:";    print open(cookieFilenameMozilla).read(os.path.getsize(cookieFilenameMozilla));    # # Netscape HTTP Cookie File    # # http://www.netscape.com/newsref/std/cookie_spec.html    # # This is a generated file!  Do not edit.     # .google.com   TRUE    /   FALSE   1421308121  PREF    ID=0e05040dd979207c:FF=0:NW=1:TM=1358236121:LM=1358236121:S=jcFid2XgXMIhPUPl    # .google.com.hk    TRUE    /   FALSE   1374047321  NID 67=klMI_Z5ZPWDjUYrWSUHIE_kYI77_ziJaL0kWRoUGThagME86LKY7H-MNa2wAMI_GklIwYcD8t82qPinxzLd4GLDbmWT0OVLCXhRj0wQDC57dTNAsTs4lhVR7Yjvj2tfn    # .google.com.hk    TRUE    /   FALSE   1421308121  PREF    ID=028f8b736db06a9a:U=6ba6d080847c8de6:FF=2:LD=zh-CN:NW=1:TM=1358236121:LM=1358236121:S=_1BcC5v3G0ZojVz8         print "4. read cookies from file";    parseAndSavedCookieFile = "parsedAndSavedCookies.txt"    parsedCookieJarFile = cookielib.MozillaCookieJar(parseAndSavedCookieFile);    #parsedCookieJarFile = cookielib.MozillaCookieJar(cookieFilenameMozilla);    print parsedCookieJarFile; #    parsedCookieJarFile.load(cookieFilenameMozilla);

    print parsedCookieJarFile; #<_MozillaCookieJar.MozillaCookieJar[,,]>
 
     
if __name__=="__main__":
    pythonAutoHandleCookie();

 

總結

Python中的cookie的自動處理,比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.