Consulta el SIS Perú automáticamente con Python | Web Scraping desde cero

 

En este video aprenderás web scraping en Python desde cero usando un caso real:

cómo consultar si una persona está registrada en el SIS (Seguro Integral de Salud del Perú).

Librerias utilizadas

requests, easyOCR

***********************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 persona en el SIS</div>

    <div class="fila">

        <input type="text" id="txtIdentificador" value="" />

       <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/Demo50.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 io

from PIL import Image

import numpy as np

import easyocr

import cv2


reader = easyocr.Reader(['en'])

def index(request):

    return render(request,"Demo50.html")


def procesar(request):

    dni=request.POST.get("data")

    rptaJson={}

    print("buscar dni "+dni)

    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://cel.sis.gob.pe/SisConsultaEnLinea",headers=header,verify=False)

        if req.status_code==200:

            html=req.text


            pos=html.find("hdfToken")

            if pos>-1:

                posValue=html.find("value=",pos)

                poscomilla=html.find("\"",posValue+7)

                token=html[posValue+7:poscomilla]

                captcha=obtenerCaptcha(sesion,token)

                header["host"]="cel.sis.gob.pe"

                header["origin"]="https://cel.sis.gob.pe"

                header["referer"]="https://cel.sis.gob.pe/SisConsultaEnLinea"

                header["content-type"]="text/plain;charset=UTF-8"

                header["token"]=token

                payload= cifrarDatos("1¬1¬"+dni+"¬¬¬¬"+captcha)

                print(payload)

                req=sesion.post("https://cel.sis.gob.pe/SisConsultaEnLinea/Consulta/siguiente",data=payload,headers=header,verify=False)

                

                if req.status_code==200:

                    rpta=req.text

                    dataDecifrada=decifrarDatos(rpta)

                    a=dataDecifrada.split("$")

                    if len(a)>2:

                        datos=a[3].split("¬")

                        rptaJson["nombres"]=datos[1]

                        rptaJson["numeroAfiliacion"]=datos[5]

                        rptaJson["tipoAsegurado"]=datos[6]

                        rptaJson["estado"]=datos[7]

                        rptaJson["tipoSeguro"]=datos[8]

                        rptaJson["tipoFormato"]=datos[10]

                        rptaJson["planBeneficio"]=datos[12]

                        rptaJson["establecimiento"]=datos[13]

                   

    except Exception as e:

        print("Error "+ str(e))

      

    return JsonResponse(rptaJson,safe=False)


def obtenerCaptcha(sesion,token):

    global reader

    headers2={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",

                "host":"cel.sis.gob.pe",

                "referer":"https://cel.sis.gob.pe/SisConsultaEnLinea",

                "token":token,

                }

    req=sesion.get("https://cel.sis.gob.pe/SisConsultaEnLinea/Consulta/crearCaptcha",headers=headers2,verify=False)

    captcha=""

    if req.status_code==200:


        imgByte=io.BytesIO(req.content)

        img=Image.open(imgByte)

        imgnp=np.array(img)

        img.save("captcha.png",format="PNG")


        gray=cv2.imread("captcha.png",0)

        thresholded = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

        cv2.imwrite("captcha2.png",thresholded)

        result=reader.readtext(gray, detail = 0, paragraph=True)

        print("capcha",result)

        if result is not None and len(result)>0:

            captcha=result[0].replace(" ","").strip().replace("~","").replace("_","").replace("-","").upper()

            print(captcha)

    if len(captcha)!=5:

        captcha=obtenerCaptcha(sesion,token)

    return captcha


def cifrarDatos(d):

    b = []

    c = len(d)

    for i in range(c):

        a=ord(d[i])

        if a<255:

            a=a+1

        else:

            a=0

        b.append(chr(a))

    print(b)

    return "".join(b)


def decifrarDatos(d):

    b = []

    c = len(d)

    for i in range(c):

        a=ord(d[i])

        if a==0:

            a=255

        else:

            a=a-1

        b.append(chr(a))

    return "".join(b)


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