python模拟浏览器保存Cookie进行会话

#! /usr/bin/env python
# -*-coding:utf- -*- 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][] #用于Django开启csrf中间件时
except:
pass
data['username']=username
data['password']=password
return data def login(self,follow_up_url, username,password,**others):
print
print '-'*,'login...','-'*
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 '^'*,'login success','^'*
except:
print '!'*,'login failure','!'*
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')
上一篇:github的使用,利用git shell命令行创建仓库并上传


下一篇:GitHub客户端和Shell的基本操作和理解