C贸mo automatizar la consulta del SOAT en Bolivia con con Python 馃殌
En este video te muestro c贸mo automatizar la consulta del SOAT en Bolivia usando Python y Web Scraping.
Vamos a crear un script real utilizando la librer铆a requests para extraer informaci贸n directamente desde la web y procesarla autom谩ticamente.**************************************HTML*****************************************
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'styles/general.css' %}" />
<style>
.cntpreview{
background: #000;
padding: 10px;
width: 50%;
min-height: 300px;
color: #fff
}
</style>
</head>
<body>
<div id="divLoading" class="wrap_loading hide">
<div class="lds-ring">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="loading_text">Procesando ...</div>
</div>
<div class="titulo">Consulta cobertura de SOAT por placa Bolivia</div>
<div class="fila">
<input type="text" id="txtIdentificador" value="2719STC,1852PHD" />
<button id="btnProcesar" class="boton">Procesar</button>
</div>
<div style="display: flex;justify-content: center;">
<pre id="txtPre" class="cntpreview"></pre>
</div>
<div>
{% csrf_token %}
</div>
<script src="{% static 'scripts/Demo55.js' %}" ></script>
</body>
</html>
**************************************JAVASSCRIPT*****************************************
window.onload=function(){
let btnProcesar=document.getElementById("btnProcesar");
btnProcesar.onclick=function(){
let txtFecha=document.getElementById("txtIdentificador").value;
let fd=new FormData();
fd.append("data",txtFecha);
servidor({url:"procesar",data:fd,responsetype:"json"}).then((data)=>{
document.getElementById("txtPre").innerHTML=JSON.stringify(data,null,2);
});
}
}
function servidor({ metodo = "post", url = null, data = null, responsetype = "text" } = {}) {
return new Promise((resolve, reject) => {
let divLoading=document.getElementById("divLoading");
if(divLoading){
divLoading.classList.remove("hide");
}
let xhr = new XMLHttpRequest();
xhr.open(metodo, url);
var csrftoken=document.getElementsByName("csrfmiddlewaretoken")[0].value;
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.responseType = responsetype;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
divLoading.classList.add("hide");
resolve(xhr.response);
}
}
xhr.onerror = function (e) {
reject(e)
}
xhr.send(data);
});
}
**************************************PYTHON*****************************************
from django.shortcuts import render
from django.http.response import HttpResponse,JsonResponse
from django.conf import settings
import requests
def index(request):
return render(request,"Demo55.html")
def procesar(request):
placa=request.POST.get("data")
rptaJson={}
print("buscar placa "+placa)
try:
header={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
}
sesion=requests.session()
req=sesion.get("https://soat.univida.bo:9097/UNIVidaNetSOATClienteFinal/Modulos_/Cliente/ConsultasVerificacionSoat/wfObtener",headers=header,verify=False)#
if req.status_code==200:
html=req.text
#print(html)
pos=html.find("__VIEWSTATE")
posValue=html.find("value=",pos)
poscomilla=html.find("\"",posValue+7)
viewstate=html[posValue+7:poscomilla]
print(viewstate)
pos=html.find("__VIEWSTATEGENERATOR",pos)
posValue=html.find("value=",pos)
poscomilla=html.find("\"",posValue+7)
VIEWSTATEGENERATOR=html[posValue+7:poscomilla]
print(VIEWSTATEGENERATOR)
pos=html.find("__EVENTVALIDATION",pos)
posValue=html.find("value=",pos)
poscomilla=html.find("\"",posValue+7)
EVENTVALIDATION=html[posValue+7:poscomilla]
print(EVENTVALIDATION)
header["origin"]="https://soat.univida.bo:9097"
header["referer"]="https://soat.univida.bo:9097/UNIVidaNetSOATClienteFinal/Modulos_/Cliente/ConsultasVerificacionSoat/wfObtener"
header["content-type"]="application/x-www-form-urlencoded"
#payload="javax.faces.partial.ajax=true&javax.faces.source=busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Aj_idt118&javax.faces.partial.execute=%40all&javax.faces.partial.render=busqueda&busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Aj_idt118=busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Aj_idt118&busqueda%3AfrmBusquedaVehiculo=busqueda%3AfrmBusquedaVehiculo&busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Acriterio%3AruatComboBox_focus=&busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Acriterio%3AruatComboBox_input=PTA&busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Aidentificador-placapta%3AruatInputText="+placa+"&busqueda%3AfrmBusquedaVehiculo%3Apnl-datosbusqueda%3Aj_idt102%3AruatCaptcha="+captcha+"&javax.faces.ViewState="+viewstate
payload = {
"__EVENTTARGET":"",
"__EVENTARGUMENT":"",
"__VIEWSTATE":viewstate,
"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
"__SCROLLPOSITIONX":"0",
"__SCROLLPOSITIONY":"98.4000015258789",
"__EVENTVALIDATION":EVENTVALIDATION,
"ctl00$MainContent$ddlCriterioBusqueda":"1",
"ctl00$MainContent$txtCriterioValor":placa,
"ctl00$MainContent$btnBuscar":"Consultar SOAT"
}
req=sesion.post("https://soat.univida.bo:9097/UNIVidaNetSOATClienteFinal/Modulos_/Cliente/ConsultasVerificacionSoat/wfObtener",data=payload,headers=header,verify=False,allow_redirects=True)
if req.status_code==200:
html=req.text
html_string = html.replace("\n", "").replace("\r", "").replace("\t", "")
keys={"placa":"MainContent_lblCriterioBusquedaValor",
"anio":"MainContent_lblGestionSoat",
"inicioCobertura":"MainContent_lblFechaCoberturaInicio",
"fincobertura":"MainContent_lblFechaCoberturaFin",
"tipoVehiculo":"MainContent_lblSoatTParVehiculoTipoDescripcion",
"tipoUso":"MainContent_lblSoatTParVehiculoUsoDescripcion",
"departamentoCirculacion":"MainContent_lblDepartamentoPc"}
pos=0
for (k,valor) in keys.items():
print(valor)
pos=html_string.find(valor,pos)
print(pos)
if pos>-1:
posmayor=html_string.find(">",pos)
posmenor=html_string.find("<",posmayor+1)
rptaJson[k]=html_string[posmayor+1:posmenor]
except Exception as e:
print("Error "+ str(e))
return JsonResponse(rptaJson,safe=False)
Comentarios
Publicar un comentario