Web scraping Tipo de Cambio SUNAT

 Aprende a obtener el tipo de cambio SUNAT usando Python y requests con web scraping sin mucho esfuerzo y fácil


***************************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 tipo cambio SUNAT</div> <div class="fila"> <select id="txtIdentificador"><option value="1">Página SUNAT</option><option value="2">Página el peruano</option><option value="3">Página SBS</option></select> <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/Demo49.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 json from datetime import timedelta, datetime import random def index(request): return render(request,"Demo49.html") def procesar(request): tipo=request.POST.get("data") print("tipo ",tipo) rptaJson={} try: if tipo=="1": rptaJson=consultaTipoCambioSunat() elif tipo=="2": rptaJson=consultaTipoCambioElperuano() else: rptaJson=consultaTipoCambioSBS() except Exception as e: print("Error "+ str(e)) rptaJson={} return JsonResponse(rptaJson,safe=False) def consultaTipoCambioSunat(): rptaJson={} try: header={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36"} sesion=requests.session() req=sesion.get("https://www.sunat.gob.pe/a/txt/tipoCambio.txt",headers=header,verify=False) if req.status_code==200: data=req.text adata=data.split("|") rptaJson={"fecha":adata[0],"compra":adata[1],"venta":adata[2]} except Exception as e: print("Error "+ str(e)) rptaJson={} return rptaJson def consultaTipoCambioElperuano(): rptaJson={} try: header={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36"} sesion=requests.session() req=sesion.get("https://elperuano.pe/Portal/_GetDolarActualizado",headers=header,verify=False) if req.status_code==200: data=req.json() adata=data["dtmFecha"] pos=adata.find("(") posfin=adata.find(")",pos+1) fecha=adata[pos+1:posfin] fechastr=datetime.fromtimestamp(int(fecha)/1000.0).strftime("%d/%m/%Y") rptaJson={"fecha":fechastr,"compra":data["intCompra"],"venta":data["intVenta"]} except Exception as e: print("Error "+ str(e)) rptaJson={} return rptaJson def consultaTipoCambioSBS(): rptaJson={} try: header={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36", "referer":"https://www.google.com/", "accept-language":"es-ES,es;q=0.9", "sec-fetch-mode":"navigate"} sesion=requests.session() req=sesion.get("https://www.sbs.gob.pe/app/pp/sistip_portal/paginas/publicacion/tipocambiopromedio.aspx?v="+str(random.randint(1,10)),headers=header,verify=False) if req.status_code==200: html=req.text pos=html.find("Tipo de Cambio al") if pos>-1: posmenor=html.find("<",pos+17) fecha=html[pos+17:posmenor].strip() posdolar=html.find("Dólar de N.A.",posmenor) posmayor=html.find(">",posdolar+18) posmenor=html.find("<",posmayor+1) compra=html[posmayor+1:posmenor] posmayor=html.find(">",posmenor+5) posmenor=html.find("<",posmayor+1) venta=html[posmayor+1:posmenor] _fecha=datetime.strptime(fecha,"%d/%m/%Y") _fecha=_fecha+ timedelta(days=1) rptaJson={"fecha":_fecha.strftime("%d/%m/%Y"),"compra":compra,"venta":venta} except Exception as e: print("Error "+ str(e)) rptaJson={} return rptaJson

Comentarios

Entradas populares de este blog

Web Scraping en Argentina: búsqueda de personas por DNI paso a paso

¡Mira Cómo Obtengo Datos de un Vehículo Solo con la Placa! (Web Scraping)

Bot whatsapp con whatsapp-web.js y nodejs