def __init__(self): # If under test mode self.test = configHelper.readMode('test') # If it is a working day. self.nightMode = configHelper.readMode('nightMode') self.partNumber = "" print("IReserve init")
def __init__(self): self.__test = configHelper.readMode('test') # construct logger instance self.__logger = self.__getLogger() self.__dao = dao.Dao(self.__test) self.__models = self.__initModelDict() self.__maindict = self.__initClients()
def reserve(self, url, clientDict, test): nightMode = configHelper.readMode("nightMode") CMPhoneNumber = configHelper.readCMPhoneNumber(test) # driver = webdriver.PhantomJS(executable_path='/usr/bin/phantomjs') driver = webdriver.Chrome() print("============== Step 1 : select your model ==================") driver.get(url) print driver.title print("================== Step 2 : login submit ===================") driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) try: eAppId = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "appleId"))) eAppId.send_keys(clientDict["appleId"]) ePwd = driver.find_element_by_id("pwd") ePwd.send_keys(clientDict["pwd"]) eSubmit = driver.find_element_by_id("sign-in") eSubmit.click() print("================ Step 3 : Registration Code ==============") # ----------- Send SMS to get registration code ---------------- # wait until page refreshed # WebDriverWait(driver, 10).until(EC.title_contains("SMS")) # smsCode = driver.find_element_by_tag_name("strong"); # print smsCode phoneNumber = configHelper.readPhoneNumber(test) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "phoneNumber"))) \ .send_keys(phoneNumber) # driver.find_element_by_xpath("//input[@id='phoneNumber']").send_keys(Keys.F12) print driver.title smsCode = driver.find_element_by_xpath("//div/p/strong").text print("smscode : " + smsCode) autosms = configHelper.readMode('autosms') if len(smsCode) > 1: if not test or autosms: CMPhoneNumber = configHelper.readCMPhoneNumber(test) # rCode = "new code" rCode = smsmode.getResrictionCode(CMPhoneNumber, smsCode) else: # Manually input rcode if len(smsCode) < 1: time.sleep(15) else: time.sleep(30) configHelper.writeRCode(rCode, clientDict["appleId"]) else: # Last rCode is still available rCode = configHelper.readRCode() print rCode driver.find_element_by_id("registrationcode").send_keys(rCode) # if not test or autosms: # # if smscode is empty, means last code is still available # # need to retrieve it from file # if len(smsCode) < 1: # rCode = configHelper.readRCode() # else: # # Send SMS and get code # rCode = smsmode.getResrictionCode(CMPhoneNumber, smsCode) # configHelper.writeRCode(rCode) # print rCode # driver.find_element_by_id("registrationcode").send_keys(rCode) # else: # if len(smsCode) < 1: # time.sleep(15) # else: # time.sleep(30) driver.find_element_by_name("submit").click() print(" --------- Step 4.1 Select TimeSlots ----------"), '\n' # --------- Select timeSlot and reserve -------------------------- # eTimeSlot = driver.find_element_by_id("time") # Don't use find_by_id, there might be multiple elements # with same id # which will cause error # time.sleep(1) WebDriverWait(driver, 10).until(EC.title_contains(u"选择时间")) print driver.title time.sleep(2) # eTimeSlot = driver.find_element_by_xpath( # "//div[contains(@class, 'select-store')]/select") # quantity = clientDict["quantity"] # eQuantity = WebDriverWait(driver, 10).until( # EC.presence_of_element_located((By.ID, "quantity"))) # time.sleep(1) eTimeSlot = WebDriverWait(driver, 10).until( EC.presence_of_element_located(( By.XPATH, "//div[contains(@class, 'select-store')]/select[contains(@name, 'selectedTimeSlotId')]" ))) allOptions = eTimeSlot.find_elements_by_tag_name("option") # get current hour now = datetime.datetime.now() curHour = now.hour print 'length: ' + str(len(allOptions)) for i, option in enumerate(allOptions): # first option is invalid if i == 0: continue text = option.get_attribute("text") print str(i) + " : " + text # Format : 下午 1:30 - 下午 2:00 arr = text.split(" ") hour = int(arr[1].split(":")[0]) # format hour to 24 hours if arr[0] == u"下午" and hour < 12: hour += 12 if nightMode and curHour < 18: if hour >= 20: option.click() break else: if hour >= curHour + 2: option.click() break if i == len(allOptions) - 1: option.click() # select:quantity # eQuatity = driver.find_element_by_id("quantity") # allOptions = eQuatity.find_elements_by_tag_name("option") # text:lastName # eLastName = WebDriverWait(driver, 10).until( # EC.presence_of_element_located((By.ID, "lastName"))) # eLastName.clear() # eLastName.send_keys(lastName) # # text:firstName # driver.find_element_by_id("firstName").clear() # driver.find_element_by_id("firstName").send_keys(firstName) # # text:email # driver.find_element_by_id("email").clear() # driver.find_element_by_id("email").send_keys(email) # select:govid # time.sleep(1) eGovid = driver.find_element_by_id("govid") allOptions = eGovid.find_elements_by_tag_name("option") for i, option in enumerate(allOptions): if i == 1: # time.sleep(1) option.click() # text:govidnumber govidnumber = clientDict["govid"] driver.find_element_by_id("govidnumber").send_keys(govidnumber) print govidnumber # button - name:submit # if not test: driver.find_element_by_name("submit").click() time.sleep(90) print driver.title error = "" eError = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, "//div[contains(@class, 'error-copy')]/h2/span"))) if eError is not None: error = eError.text print(eError.text) resultList = [error] return resultList finally: driver.close()
import os import time import signal import traceback import sys import imp import datetime import requests import logging import configHelper import dao import myutil # If it's under test mode test = configHelper.readMode('test') logger = logging.getLogger('mylogger') logger.setLevel(logging.DEBUG) fh = logging.FileHandler('iphoneStock.log') fh.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) d = dao.Dao(test)
def __stepTimeSlot(self, url, govid, govidType, quantity): print("------------- Step 4.1 Select TimeSlots ---------------"), '\n' timeSlotURL = url + "&ajaxSource=true&_eventId=context&dims=" print("request URL: " + timeSlotURL) self.__session.headers = self.__getJSONHeaders() r = self.__session.get(timeSlotURL) print('--------[timeslots JSON RESULT]---' + r.text + '-------', '\n') error_str = self.__json_errmsg(r.text, "errors") if len(error_str) > 0: raise errors.IReserveSMSError(error_str) reserveDict = json.loads(r.text) # Finde the right time # get current hour timeslots = reserveDict["timeslots"] curHour = datetime.datetime.now().hour selectedId = "" selectedTime = "" # for timeslot in timeslots: for i, option in enumerate(timeslots): text = option['formattedTime'] curId = option['timeSlotId'] # Format : 下午 1:30 - 下午 2:00 arr = text.split(" ") hour = int(arr[1].split(":")[0]) # format hour to 24 hours if arr[0] == u"下午" and hour < 12: hour += 12 nightMode = configHelper.readMode("nightMode") if nightMode and curHour < 18: if hour >= 20: selectedId = curId selectedTime = text break else: if hour >= curHour + 2: selectedId = curId selectedTime = text break if i == len(timeslots) - 1: selectedId = curId selectedTime = text print(selectedId) print(selectedTime), '\n' # print (timeslots) print("-------------- Step 4.2 Submit Reserve ---------------"), '\n' data = { "selectedStoreNumber": reserveDict['selectedStoreNumber'], # "selectedPartNumber": partNumber, "selectedContractType": "UNLOCKED", "selectedQuantity": quantity, "selectedTimeSlotId": selectedId, "lastName": reserveDict["lastName"], "firstName": reserveDict["firstName"], "email": reserveDict["email"], "selectedGovtIdType": govidType, "govtId": govid, "p_ie": reserveDict["p_ie"], "_flowExecutionKey": reserveDict["_flowExecutionKey"], "_eventId": "next", "submit": "", } self.__session.headers = myutil.getHTMLHeaders() print(data), '\n' print("request URL: " + url), '\n' sleeptime = configHelper.readConfig('submitTimeSleep') print("current sleep time is : " + str(sleeptime)) time.sleep(sleeptime) r = self.__session.post(url, data=data) r = self.__session.get(r.url) url = r.url + "&ajaxSource=true&_eventId=context&dims=" print("request URL: " + url), '\n' self.__session.headers = self.__getJSONHeaders() r = self.__session.get(url) print('--------[Sumit Error JSON RESULT]---' + r.text + '-----', '\n') error_str = self.__json_errmsg(r.text, "errors") if len(error_str) > 0: if error_str == "availabilityError": raise errors.IReserveAvailError(error_str) else: raise errors.IReserveReserveError(error_str)
def __stepRCode(self, url, appleId): print("================= Step 3 : Registration Code ================") print('---------- step 3.1 Request SMS JSON ------------------') rCodeURL = url + "&ajaxSource=true&_eventId=context" print(rCodeURL, '\n') self.__session.headers = self.__getJSONHeaders() print("request URL: " + rCodeURL), '\n' r = self.__session.get(rCodeURL) print('--------[SMS JSON RESULT]---' + r.text + '---------------') if not r.text: raise errors.IReserveLoginFastError("登录太快了,请等几秒钟") print('---------- step 3.2 Send SMS & get RCode ------------'), '\n' rCode = "" # If smscode is already sended print(json.loads(r.text)), '\n' rcDict = json.loads(r.text) smsCode = rcDict['keyword'] print('SMS Code: ' + rcDict['keyword']) print(self.__test) p_ie = rcDict["p_ie"] flowExecutionKey = rcDict['_flowExecutionKey'] firstTime = rcDict['firstTime'] autosms = configHelper.readMode('autosms') if not self.__test or autosms: phoneNumber = configHelper.readPhoneNumber(False) else: phoneNumber = configHelper.readPhoneNumber(True) print("phone number: " + phoneNumber) if firstTime: if not self.__test or autosms: CMPhoneNumber = configHelper.readCMPhoneNumber(self.__test) # rCode = "new code" rCode = smsmode.getResrictionCode(CMPhoneNumber, smsCode) else: # Manually input rcode rCode = raw_input("please input registration code:") # configHelper.writeRCode(rCode, appleId) curTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.__dao.insertOrUpdateRCode(rCode, phoneNumber, appleId, curTime) else: # Last rCode is still available # rCode = configHelper.readRCode() rCode = self.__dao.getRCode(phoneNumber, appleId)[0][1] print('registration code: ' + rCode) self.__session.headers = myutil.getHTMLHeaders() data = { "phoneNumber": phoneNumber, "selectedCountryCode": 86, "registrationCode": rCode, "submit": "", "_flowExecutionKey": flowExecutionKey, "_eventId": "next", "p_ie": p_ie, "dims": "" } print("request URL: " + url), '\n' r = self.__session.post(url, data=data) print(r.url), '\n' return r.url
def stepRCode(url): print("========================= Step 3 : Registration Code =========================") print ('---------- step 3.1 Request SMS JSON ------------------') rCodeURL = url + "&ajaxSource=true&_eventId=context" print rCodeURL, '\n' session.headers = { "Accept":"application/json, text/javascript, */*; q=0.01", "Accept-Encoding":"gzip, deflate, br", "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Connection":"keep-alive", "Content-Type":"application/json", "X-Requested-With":"XMLHttpRequest", } print ("request URL: " + rCodeURL), '\n' r = session.get(rCodeURL) print '--------[SMS JSON RESULT]---' + r.text + '---------------' print ('---------- step 3.2 Send SMS & get RCode ------------'), '\n' rCode = "" # If smscode is already sended print (json.loads(r.text)), '\n' rcDict = json.loads(r.text) smsCode = rcDict['keyword'] print 'SMS Code: ' + rcDict['keyword'] global partNumber partNumber = rcDict['selectedPartNumber'] p_ie = rcDict["p_ie"] flowExecutionKey = rcDict['_flowExecutionKey'] firstTime = rcDict['firstTime'] if firstTime: autosms = configHelper.readMode('autosms') if not test or autosms: CMPhoneNumber = configHelper.readCMPhoneNumber(test) # rCode = "new code" rCode = smsmode.getResrictionCode(CMPhoneNumber, smsCode) else: # Manually input rcode rCode = raw_input("please input registration code:") configHelper.writeRCode(rCode) else: # Last rCode is still available rCode = configHelper.readRCode() print rCode headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch, br", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Connection": "keep-alive", "Content-Type":"application/x-www-form-urlencoded", # "Host":"reserve-cn.apple.com", # "Referer":"https://reserve.cdn-apple.com/CN/zh_CN/reserve/iPhone/availability?channel=1", "Upgrade-Insecure-Requests":1, "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" } phoneNumber = configHelper.readPhoneNumber(test) data = { "phoneNumber":phoneNumber, "selectedCountryCode":86, "registrationCode":rCode, "submit":"", "_flowExecutionKey":flowExecutionKey, "_eventId":"next", "p_ie":p_ie, "dims":"" } session.headers = headers print ("request URL: " + url), '\n' r = session.post(url, data=data) print (r.url), '\n' return r.url
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests import urlparse import json from pprint import pprint import datetime import time import smsmode import configHelper test = configHelper.readMode('test') # If it is a working day. nightMode = configHelper.readMode('nightMode') partNumber = "" session = requests.Session() # ==================== Step 1 : select your model ============================ def stepModelSel(url): print("========================= Step 1 : select your model =========================") print("------------------------- Step 1.1 select your model and submit -------------------------"), '\n' # Modify request headers headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch, br", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4", "Connection": "keep-alive", "Upgrade-Insecure-Requests":1,