1. 程式人生 > >python請求時cookie處理

python請求時cookie處理

最近想寫一個自動測試專案全流程的指令碼,由於介面是 http 協議的且許多介面需要登陸,所以需要處理cookie,發現實現起來很簡單,如下:
#!python
# -*- coding: utf-8 -*-

import cookielib, urllib2


def testWithCookie():
    '''
        自動處理 cookie
    '''
    url1 = 'http://domain.com/login?xxxx'
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    resp = urllib2.urlopen(url1)
    print(resp.read())
    print cj._cookies.values()
    url2 = 'http://domain.com/xxx'
    resp = urllib2.urlopen(url2)
    print resp.read()


if __name__ == '__main__':
    testWithCookie()

其中 url2 是需要登陸後才能訪問的,否則會返回錯誤,通過輸出返回結果很容易判斷出cookie生效了