Commit 028fbbc4 by Luciano Barletta

finished selenium

1 parent b4298bf5
#-*- coding: utf-8 -*- #-*- coding: utf-8 -*-
from flask import Flask, render_template, request, url_for from flask import Flask, render_template, request, url_for
from iselenium.py import SeleniumInterface as SI from iselenium import SeleniumInterface as SI
import random import random
app = Flask(__name__) app = Flask(__name__)
data = { data = {
"header" : { "header" : {
"dominio" : "dom", "patente" : "ABC123",
"fecha" : "15-01-2019", "fecha" : "15-01-2019",
"hora" : "11:10"
}, },
"alineador" : { "alineador" : {
"eje_delan" : "0.000" "eje_delantero" : "0.000"
}, },
"suspension" : [ "suspension" : [
{ {
"ren_izq" : "0.000", "rendimiento_izquierdo" : "0.000",
"peso" : "0.000", "peso_estatico" : "0.000",
"ren_der" : "0.000", "peso_dinamico" : "0.000",
}, "rendimiento_derecho" : "0.000"
{
"ren_izq" : "0.000",
"peso" : "0.000",
"ren_der" : "0.000",
} }
], ],
"frenos" : [ "frenos" : [
{ {
"f_izq" : "0.000", "fuerza_izquierda" : "0.000",
"res_izq" : "0.000", "resistencia_izquierda" : "0.000",
"ov_izq" : "0.000", "ovalidad_izquierda" : "0.000",
"peso" : "0.000", "peso_estatico" : "0.000",
"f_der" : "0.000", "peso_dinamico" : "0.000",
"res_der" : "0.000", "fuerza_derecha" : "0.000",
"ov_der" : "0.000", "resistencia_derecha" : "0.000",
}, "ovalidad_derecha" : "0.000"
{
"f_izq" : "0.000",
"res_izq" : "0.000",
"ov_izq" : "0.000",
"peso" : "0.000",
"f_der" : "0.000",
"res_der" : "0.000",
"ov_der" : "0.000",
},
{
"f_izq" : "0.000",
"res_izq" : "0.000",
"ov_izq" : "0.000",
"peso" : "0.000",
"f_der" : "0.000",
"res_der" : "0.000",
"ov_der" : "0.000",
},
{
"f_izq" : "0.000",
"res_izq" : "0.000",
"ov_izq" : "0.000",
"peso" : "0.000",
"f_der" : "0.000",
"res_der" : "0.000",
"ov_der" : "0.000",
} }
], ],
"trasero" : { "trasero" : {
"f_izq" : "0.000", "fuerza_izquierda" : "0.000",
"f_der" : "0.000" "fuerza_derecha" : "0.000",
"peso_estatico" : "0.000",
"peso_dinamico" : "0.000"
}, },
"gaseshumos" : { "gaseshumos" : {
"co" : "0.000", "co" : "0.000",
"hc" : "0.000", "hc" : "0.000",
"med" : "0.000" "opacidad_logaritmica" : "0.000"
} }
} }
@app.route('/') @app.route('/')
def main(): def main():
plate = "SLV350" plate = "GXN560"
s = SI(SI.Chrome) s = SI(SI.Chrome)
login(s) form = [
gototec(s) {
"rendimiento_izquierdo" : "0",
"rendimiento_derecho" : "0",
},
{
"rendimiento_izquierdo" : "0",
"rendimiento_derecho" : "0",
}
]
answer = {
"header" : {},
"alineador" : {},
"suspension" : [],
"frenos" : [],
"trasero" : {},
"gaseshumos" : {},
}
answer['header']['patente'] = plate.upper()
try:
answer = login(s, answer)
except:
return "Error en el login."
try:
answer = gototec(s, answer)
except:
return f"Error yendo a las especificaciones técnicas del dominio '{plate}'."
#try:
answer = readdata(s, answer)
#except:
# return f"Error leyendo datos de la patente '{plate}'."
#try:
answer = extradata(form, answer)
#except:
# return f"Error completando datos extra de la patente '{plate}'."
return render_template( return render_template(
"resultados.html", "resultados.html",
data = readdata(s) data = answer
) )
def login(s): def login(s, r):
s.get("https://rto.cent.gov.ar/rto") s.get("https://rto.cent.gov.ar/rto")
login = s.find(SI.By.NAME, "j_username") login = s.find(SI.By.NAME, "j_username")
...@@ -98,12 +108,22 @@ def login(s): ...@@ -98,12 +108,22 @@ def login(s):
button = s.find(SI.By.ID, "submit") button = s.find(SI.By.ID, "submit")
button.click() button.click()
def gototec(s): return r
def gototec(s, r):
s.get("https://rto.cent.gov.ar/rto/RTO/listaDePlanillas") s.get("https://rto.cent.gov.ar/rto/RTO/listaDePlanillas")
# children of parent of td with innerText = plate # children of parent of td with innerText = plate
columns = s.children(s.parent( s.find(SI.By.XPATH, f"//tr//td[text()='{plate}']") )) found = False
# fecha while(found == False):
try:
columns = s.children(s.parent( s.find(SI.By.XPATH, f"//tr//td[text()='{r['header']['patente']}']") ))
r['header']['fecha'], r['header']['hora'] = s.readElement(columns[4]).split(" ")
found = True
except:
# next page
s.find(SI.By.XPATH, "//a[text()='Siguiente']").click()
# get all a tags and click the last one # get all a tags and click the last one
options = s.findFromElement(columns[-1], SI.By.TAG_NAME, "a", "1-") options = s.findFromElement(columns[-1], SI.By.TAG_NAME, "a", "1-")
...@@ -115,53 +135,75 @@ def gototec(s): ...@@ -115,53 +135,75 @@ def gototec(s):
if tec.get_attribute("innerText") == "ir a Datos Técnicos": if tec.get_attribute("innerText") == "ir a Datos Técnicos":
tec.click() tec.click()
def readdata(s): return r
answer = {
"header" : {}, def readdata(s, r):
"alineador" : {}, reach = lambda id: lambda s: s.readInput( s.find(s.By.ID, id) )
"suspension" : [],
"frenos" : [], # alineacion
"trasero" : {}, r['alineador']['eje_delantero'] = attempt_do(reach("deriva"), default = "?")(s)
"gaseshumos" : {},
} # suspension
for i in range(2):
sus = {}
sus['fuerza_izquierda'] = attempt_do(reach(f"fuerzaIzq-{i}"), default = "?")(s)
sus['fuerza_derecha'] = attempt_do(reach(f"fuerzaDer-{i}"), default = "?")(s)
r['suspension'].append(sus)
# frenos
frenos = s.find(SI.By.XPATH, "//table[@class='tabla_ensayo']/tbody//tr[@class='odd' or @class='even']","1-4")
for i in range(len(frenos)):
fre = {}
fre['peso_estatico'] = attempt_do(reach(f"pesoBascula-{i}"), default = "?")(s)
fre['peso_dinamico'] = attempt_do(reach(f"pesoMaximo-{i}"), default = "?")(s)
fre['fuerza_izquierda'] = attempt_do(reach(f"fuerzaIzq-{i}"), default = "?")(s)
fre['fuerza_derecha'] = attempt_do(reach(f"fuerzaDer-{i}"), default = "?")(s)
r['frenos'].append(fre)
# Tables # freno trasero
frenos = s.find(SI.By.XPATH, "//table[@class='tabla_ensayo']")
estacionamiento = s.find(SI.By.ID, "tablaFrenoEstacionario")
medidas = s.find(SI.By.TAG_NAME, "fieldset")
ejes = s.findFromElement(frenos, SI.By.XPATH, "/tbody//tr[@class='even' or @class='odd']", "1-4") r['trasero']['peso_estatico'] = attempt_do(reach(f"pesoBasculaEst-0"), default = "?")(s)
r['trasero']['peso_dinamico'] = attempt_do(reach(f"pesoMaximoEst-0"), default = "?")(s)
r['trasero']['fuerza_izquierda'] = attempt_do(reach(f"fuerzaIzqEst-0"), default = "?")(s)
r['trasero']['fuerza_derecha'] = attempt_do(reach(f"fuerzaDerEst-0"), default = "?")(s)
for e in ejes: # gases y humos
c = s.children(e); a = []
# make a map from numbers to string indices? 1 => PesoEstatico, ... r['gaseshumos']['opacidad_logaritmica'] = attempt_do(reach(f"opacidadLogaritmica"), default = "?")(s)
# useful for random generated values too r['gaseshumos']['co'] = attempt_do(reach(f"co"), default = "?")(s)
r['gaseshumos']['hc'] = attempt_do(reach(f"hc"), default = "?")(s)
# for the 2nd, 3rd, 5th and 6th column, attempt to read the value return r
for column in [c[1], c[2], c[4], c[5]]:
# reach: gets the first input child and reads it
reach = lambda c, s: s.read(s.findFromElement(c,SI.By.TAG_NAME, "input"))
a.append(attempt_do(reach, column, s))
answer.append(a) def extradata(form, r):
# eje delantero res = lambda: round(random.random() * 0.9 + 0.05, 2)
ov = lambda: round(random.random() * 39 + 0.5, 2)
for i in range(len(r['suspension'])):
r['suspension'][i]['rendimiento_izquierdo'] = form[i]['rendimiento_izquierdo']
r['suspension'][i]['rendimiento_derecho'] = form[i]['rendimiento_derecho']
# fuerza freno estacionamiento for i in range(len(r['frenos'])):
# co r['frenos'][i]['resistencia_izquierda'] = res()
# hc r['frenos'][i]['resistencia_derecha'] = res()
# opacidad log r['frenos'][i]['ovalidad_izquierda'] = ov()
r['frenos'][i]['ovalidad_derecha'] = ov()
return answer return r
# Executes the lambda with the arguments, with try except # Executes the lambda with the arguments, with try except
def attempt_do(f, *args, **kwargs, default = ""): def attempt_do(f, default = "", error = ""):
def inner(*args, **kwargs):
try: try:
return f(*args, **kwargs) return f(*args, **kwargs)
except: except:
if error != "":
raise Exception(error)
return default return default
return inner
# Inicio del servicio # Inicio del servicio
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -3,13 +3,15 @@ from selenium.webdriver.common.keys import Keys ...@@ -3,13 +3,15 @@ from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as Wait from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support import expected_conditions as EC
import time
class SeleniumInterface: class SeleniumInterface:
Chrome = "Chrome" Chrome = "Chrome"
By = By() By = By()
Keys = Keys() Keys = Keys()
Timeout = 10 Timeout = 1
PageChangeWait = 1
def __init__(self, driverType): def __init__(self, driverType):
self.driver = self._getDriver(driverType) self.driver = self._getDriver(driverType)
...@@ -20,6 +22,7 @@ class SeleniumInterface: ...@@ -20,6 +22,7 @@ class SeleniumInterface:
raise NoSuchDriver(self.driver) raise NoSuchDriver(self.driver)
def get(self, url): def get(self, url):
time.sleep(SeleniumInterface.PageChangeWait)
self.driver.get(url) self.driver.get(url)
def find(self, by, lookup, select = "1"): def find(self, by, lookup, select = "1"):
...@@ -55,8 +58,11 @@ class SeleniumInterface: ...@@ -55,8 +58,11 @@ class SeleniumInterface:
element.send_keys(keys) element.send_keys(keys)
def read(self, element): def readInput(self, input):
return element.get_attribute("value") return input.get_attribute("value")
def readElement(self, element):
return element.get_attribute("innerText")
def _resolve(self, selector, elements): def _resolve(self, selector, elements):
div, rev, answer = selector.split("-"), False, [] div, rev, answer = selector.split("-"), False, []
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!