import urllib,urllib2,cookielibimport reimport datetime class Loginjx: #偽裝browser header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} username = '' passwd = '' cookie = None #cookie對象 cookiefile = './cookies.dat' #cookie臨時存放地 user = '' def __init__(self,username,passwd): self.username = username self.passwd = passwd #cookie設定 self.cookie = cookielib.LWPCookieJar() #自訂cookie存放 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie)) urllib2.install_opener(opener) #登陸 def login(self): #請求參數設定 postdata = { 'username':self.username, 'password':self.passwd, 'cookietime':2592000, 'dosubmit':'登入', 'forward':'' } postdata = urllib.urlencode(postdata) #發起請求 req = urllib2.Request( url='http://www.gjjx.com.cn/index.php?m=member&c=index&a=login', data= postdata,#請求資料 headers = self.header #要求標頭 ) result = urllib2.urlopen(req).read() result = str(result) self.user = self.username self.cookie.save(self.cookiefile)#儲存cookie if '登陸成功' in result: print("%s 你已成功登陸。---------\n" %(self.user)) flag = True else: print("%s 登陸可恥的失敗鳥") flag = False return flag def get_uid(self): uid_url = urllib2.Request( url='http://www.gjjx.com.cn/index.php?m=member&c=index&a=appointment', headers = self.header ) auth = urllib2.urlopen(uid_url).read() result = str(auth) uid = re.findall( '''學員證號<span>(\d+)</span>''', result) return uid[0] def order_class(self,uid="61394720",yyrq="25-DEC-11",sd="5",cnbh="32220",traint="2"): base_url = "http://www.gjjx.com.cn/index.php?m=member&c=index&a=bpk&" query_param = "id=%s&yyrq=%s&sd=%s&cnbh=%s&traint=%s" % (uid,yyrq,sd,cnbh,traint) print base_url + query_param uid_url = urllib2.Request( url= (base_url + query_param), headers = self.header ) auth = urllib2.urlopen(uid_url).read() result = str(auth) if "到期" in result: return "timeout" elif "成功" in result: return "ok" elif "同一車時不能重複預約" in result: return "ok" else: return "failed" print("Requesting......")#使用者名稱密碼login = Loginjx('username','password')#時段 5 - 07:00--12:00 6 - 13:00--18:00sd = "5"#場內編號cnbh = "32221"#預約日期order_date = '2011-12-25'yyrq = datetime.datetime.strptime(order_date,'%Y-%m-%d').strftime('%d-%b-%y').upper();#yyrq="25-DEC-11"#科目類別 0 樁訓 2 類比 ....traint="2" flag = Falseorder_ok = False while flag == False: flag = login.login() if flag: uid = login.get_uid() while order_ok == False: result = login.order_class(uid=uid,yyrq=yyrq,sd=sd,cnbh=cnbh,traint=traint) if result == "timeout": print("逾時!重新登入!") flag = False order_ok = False elif result == "failed": print("正在不斷嘗試") pass else: order_ok = True flag = True print("不小心成約車功了!!")