Re-wrote the script timed appointment of a stadium, Southeast University, the use of selenium and chromedriver realize, tesseract identification code

The last write semi-finished products is urllib library directly to post the form, but now is not available, mainly in the field of post request, additional several unknown value, and encrypted password is used in ase128, I'm lazy to achieve. 
Just try selenium, selenium is a good module for automated testing, the browser can be directly mobilized, simulate human input operations such as clicking, and very easy to use, but it is relatively low efficiency, because many operations and other page elements to load before they can find out.

This not only wrote the script, also set up a website to accept reservations, and written to the database, 08:01 every morning appointment script execution, interest or needs of students can be seen here, http: //116.62.5.101: 8000 ,
later would write an article about how to deploy server based on the chrome browser and chromdriver flask websites, databases, selenium, tesseract4.0, no interface.



selenium core use is to use the selector to find the page corresponding element as an object, for example:
Bro is a selenium in webdriver of a browser object, you can use find_element_by way to find elements by name, id, class,
if these none of the elements, you can use xpath, xpath small partners who are interested can go to learn more about, but the easiest way is to open after the F12 developer mode, right-responsive element can copy it xpath.

 

 

tesseract 是一个识别引擎,用于识别验证码





import pymongo
import schedule
import time
import pytesseract
from PIL import Image
from multiprocessing import Pool
from bson import ObjectId
from selenium import webdriver
import datetime
import random
import os


def addmates(matesid,framenum,bro):

button_addmates = bro.find_element_by_id("handle-add")
button_addmates.click()
bro.switch_to.frame("xubox_iframe"+str(framenum))
input_matesid = bro.find_element_by_id("cardNo")
input_matesid.send_keys(matesid)
button_findmate = bro.find_element_by_class_name("search-id")
button_findmate.click()
input_existmates = bro.find_elements_by_class_name("user")
oldcontacts = []
for input_existmate in input_existmates:
# print(input_existmate.get_attribute("textContent"))
oldcontacts.append(input_existmate.get_attribute("textContent").strip())

time.sleep(1)
# print(bro.page_source)
input_newcontact = bro.find_element_by_id("contact")
# print(input_newcontact.get_attribute("textContent"))
newcontact = input_newcontact.get_attribute("textContent")

if newcontact not in oldcontacts:
button_addtocontacts = bro.find_element_by_class_name("add-user")
button_addtocontacts.click()
time.sleep(1)
else:
for input_existmate in input_existmates:
if input_existmate.get_attribute("textContent").strip() == newcontact:
checkbox = input_existmate.find_element_by_name("user")
checkbox.click()
time.sleep(1)
button_submitaddmates = bro.find_element_by_class_name("del-all-users")
button_submitaddmates.click()
break


# ssl._create_default_https_context = ssl._create_unverified_context
def main(reserverdic,orderid):

#隐藏浏览器界面
option = webdriver.ChromeOptions()
option.add_argument('headless')
option.add_argument('--no-sandbox')
bro = webdriver.Chrome(options=option)
# bro = webdriver.Chrome()
print("Chrome 已启动")
url = 'https://newids.seu.edu.cn/authserver/login?goto=http://my.seu.edu.cn/index.portal'


bro.get(url)
# print(bro.page_source)
#bro.save_screenshot("ddd.png")
#print("saved")
# 登录预约系统
id=reserverdic["idpwd"]["ssid"]
pwd=reserverdic["idpwd"]["pwd"]
time.sleep(3)
input_username = bro.find_element_by_id("username")
input_password = bro.find_element_by_id("password")
input_username.send_keys(id)
input_password.send_keys(pwd)
# print(input_username)
# print(input_password)

# Plurality of class can not directly use the following form find_element_by_class
botton_login = bro.find_element_by_css_selector ( "[class = 'auth_login_btn Primary Full_width']")
botton_login.click ()

# URL3 = "http://yuyue.seu.edu.cn /eduplus/order/initOrderIndex.do?sclId=1 "
# bro.get (URL3)
# open Scheduler
info reserverdic = [" info "]
# info = {
# 'dayInfo':" 2018-11-23 ",
# 'itemId':. 7,
# 'Time': "12 is: 00-13: 00"
#}
# = INFOURL urllib.parse.urlencode (info)
"" "
'itemId':. 7, Jiulonghu ping-pong, 1-3 people
'itemId': 8, Jiulonghu basketball, 9-14 audience, half-5-8
'itemId': 9, Jiulonghu volleyball, 4-15 person
'itemId': 10, Jiulonghu badminton, 1-5 people
'itemId': 11, Dragon Lake dance, non-mandatory
'itemId': 12, Dragon Lake fitness, non-mandatory
'itemId': 13, Dragon Lake martial arts, non-mandatory
'itemId': 14, Dragon Lake taekwondo, non Required
'itemId': 15, four arches badminton, 1-3 people
'itemId': 16, four arches ping-pong, 1-3 people
'itemId': 17, four arches tennis, 1-3 people
"" "

URL2 =" http://yuyue.seu.edu.cn/eduplus/order/initEditOrder.do?sclId=1&dayInfo="+info['dayInfo']+"&itemId="+info['itemId']+"&time="+ info [ "Time"]
# Print (url2)
# bro.execute_script ( "window.open ()")
# bro.switch_to.window (bro.window_handles [1])
bro.get (url2)

# basketball half-court deal with the whole field
basketball = reserverdic [ "phonemate"]["halffull"]
if basketball == 2:
buttonhalffull = bro.find_elements_by_name("orderVO.useMode")
buttonhalffull[1].click()
#添加电话
phonenumber = reserverdic["phonemate"]["phone"]
input_phone = bro.find_element_by_id("phone")
input_phone.clear()
input_phone.send_keys(phonenumber)

#添加好友
framenum=0
for eachmate in reserverdic["phonemate"]["mateid"]:
framenum+=1
addmates(eachmate,framenum,bro)
time.sleep(1)



#处理验证码
screenshot = str(random.randint(1,100000))+'screenshot.png'
validcodeshot = str(random.randint(1,100000))+'validateimage.png'
bro.get_screenshot_as_file(screenshot)
img = bro.find_element_by_xpath('//*[@id="fm"]/table/tbody/tr[6]/td[2]/img')
left = int(img.location['x'])
top = int(img.location['y'])
right = int(img.location['x'] + img.size['width'])
bottom = int(img.location['y'] + img.size['height'])

# 通过Image处理图像
im = Image.open(screenshot)
im = im.crop((left, top, right, bottom))
im.save(validcodeshot)

img = Image.open(validcodeshot)
validcode = pytesseract.image_to_string(img)
# print(validcode)

input_validcode = bro.find_element_by_id("validateCode")
input_validcode.send_keys(validcode)
button_reserve = bro.find_element_by_id("do-submit")
button_reserve.click()

os.remove(screenshot)
os.remove(validcodeshot)
time.sleep(1)



try:
alertcontent=bro.find_element_by_css_selector("[class='xubox_msg xubox_text']")
if alertcontent.get_attribute("textContent"):
updatestatus(orderid, alertcontent.get_attribute("textContent")+",预约失败")
print(alertcontent.get_attribute("textContent"), "预约失败")
bro.quit()
return 0
except Exception:
bro.quit()
updatestatus(orderid,"预约成功")
print("预约成功")
return 1


def mmain(): # reserverdic1 = {
Test #

# "Idpwd": {
# 'SSID': 220 187 988,
# 'pwd': "MIMA"
#},
# "info": {
# 'dayInfo': "2019-09-02",
# 'itemId': ". 7 ",
# 'Time': '12: 00-13: 00 '
#},
#" phonemate ": {
#" Phone ": 1885187965558,
#" mateid ": [220 184 346], all friends List # ID
#" halffull " : 1 # 1 represents the whole, 2 indicates half, the non-default bit 1 basketball, or the empty
#}
#}
# reserverdic2 = {
# "idpwd": {
# 'SSID': 220 175 358,
# 'pwd': "mima"
# },
# "info": {
# 'DayInfo': "2019-09-08",
# 'itemId': ". 7",
# 'Time': '17: 00-18: 00 '
#},
# "phonemate": {
# "Phone": 18,851,879,658,
# "mateid": [220 184 348], all friends List # ID
# "halffull": # 1 represents an audience, 2 denotes half, the non-default bit 1 basketball, or the empty
#}
#}
# = Groups [ reserverdic1, reserverdic2]


OrderList = getorderlist ()
IF not OrderList:
Print (str (datetime.date.today ()), "no orders")

the pool = Pool ()
pool.map (doorder, OrderList)

# pool.map (main , Groups)


DEF doorder (the Order):
the try:
print("process order", order)
main(order[0], order[1])
except Exception:
newstutas = "预约失败,检查提交信息是否出错"
updatestatus(order[1], newstutas)
print(newstutas)


def getorderlist():


today=datetime.date.today()
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["order"]
mycol = mydb["order"]
findresult = mycol.find({'date': str(today)}, {"reservedic": 1,"_id":1})
orderlist=[]
for x in findresult:
orderlist.append([x["reservedic"],x["_id"]])

return orderlist


def updatestatus(orderid, newinfo):
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["order"]
mycol = mydb["order"]
mycol.update_one({ "_id" : ObjectId(orderid)},{ "$set": { "status": newinfo } })


if __name__ == '__main__':
# mmain()

mmain()


# schedule.every().day.at('08:00').do(mmain)
# while True:
# schedule.run_pending()

Guess you like

Origin www.cnblogs.com/CooperXia-847550730/p/11479752.html