python模拟浏览器保存Cookie进行会话
#! /usr/bin/env python # -*-coding:utf-8 -*- import urllib import urllib2 import cookielib class NetRobot: def __init__(self, baseurl): self.cj = cookielib.CookieJar() self.baseurl = baseurl self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj)) urllib2.install_opener(self.opener) def getData(self,username,password,**data): print 'origin data:',data self.opener.open(self.baseurl) try: data['csrfmiddlewaretoken'] = [x.value for x in self.cj if "csrftoken"==x.name][0] #用于Django开启csrf中间件时 except: pass data['username']=username data['password']=password return data def login(self,follow_up_url, username,password,**others): print print '-'*25,'login...','-'*25 login_url = self.baseurl + follow_up_url data = self.getData(username, password, **others) post_data = urllib.urlencode(data) print post_data header = {'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'} #假装是浏览器 request = urllib2.Request(login_url, post_data, header) #构造post请求 try: self.opener.open(request) #提交请求 print '^'*25,'login success','^'*25 except: print '!'*25,'login failure','!'*25 print def visit(self, follow_up_url): request = urllib2.Request(self.baseurl + follow_up_url) content = self.opener.open(request) print content.read() if __name__ == '__main__': nr = NetRobot('http://192.168.1.100') #指定网站根路径 nr.login('/login/', 'user', 'password', hidRem='') #此处假设需要额外的的hiRem参数 nr.visit('/api/folders/15/?format=json')