Cómo automatizar la consulta de patentes de vehículos en Chile usando Python
En este video te muestro cómo consultar patentes de vehículos en Chile usando Python mediante Web Scraping.
Construimos un script paso a paso para obtener información de un vehículo a partir de su patente, ideal para proyectos de automatización, análisis de datos o aprendizaje práctico de Python.
-Tecnologías usadas:
Python, Web Scraping, Requests
***********************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 vehiculo por placa Chile</div>
<div class="fila">
<input type="text" id="txtIdentificador" value="GWKG64,GKSB78" />
<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/Demo53.js' %}" ></script>
</body>
</html>
***********************JAVASCRIPT**********************
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
import time
import hmac
import hashlib
import json
def index(request):
return render(request,"Demo53.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://www.patentechile.com/",headers=header,verify=False)
if req.status_code==200:
header["origin"]="https://www.patentechile.com"
header["referer"]="https://www.patentechile.com/"
header["content-type"]="application/json"
timestamp = str(int(time.time()))
print(timestamp)
valor="vehiculo|"+placa+"|"+timestamp
valorcifrado=cifrarData(valor)
print(valorcifrado)
payload={"opt":"vehiculo","valor":placa,"x":valor,"z":valorcifrado}
req=sesion.post("https://www.patentechile.com/v3/token",data=json.dumps( payload),headers=header,verify=False)
if req.status_code==200:
rpta=req.json()
print(rpta)
dtSesion=sesion.cookies.get_dict()
print(dtSesion)
if "status" in rpta and rpta["status"]:
header["content-type"]="application/x-www-form-urlencoded"
token=rpta["jwt"]
payload="q="+token
print(payload)
req=sesion.post("https://www.patentechile.com/resultados/",data=payload,headers=header,verify=False)
print(req.status_code)
if req.status_code==200:
html=req.text
pos=html.find("Información de propietario")
if pos>-1:
keys=["RUT","Nombre","Patente","Tipo","Marca","Modelo","Año","Color","Motor","Chasis","Procedencia","Fabricante"]
for key in keys:
pos=html.find(key,pos)
if pos>-1:
postd=html.find("<td>",pos)
posmenor=html.find("<",postd+4)
if key=="Año":
key="Anio"
rptaJson[key]=html[postd+4:posmenor]
except Exception as e:
print("Error "+ str(e))
return JsonResponse(rptaJson,safe=False)
def cifrarData(mensaje):
secret = "b708574124a2742b5eecab4993a7f3e91528b8a99d38e1a663b2fcbe92e38a8c"
hmac_result = hmac.new(
secret.encode("utf-8"),
mensaje.encode("utf-8"),
hashlib.sha256
).hexdigest()
return hmac_result
Comentarios
Publicar un comentario