標籤:
#! /usr/bin/env python# -*-coding:utf-8 -*-import urllibimport urllib2import cookielibclass 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‘)
python類比瀏覽器登陸