Web Scraping MASIVO antecedentes en Colombia con Python

 En este video aprenderás a consultar antecedentes en Colombia utilizando Python, Requests y técnicas de Web Scraping.

Te muestro paso a paso cómo hacer consultas individuales y masivas de forma automatizada, ideal para proyectos de automatización, análisis de datos o desarrollo backend.

🔧 Tecnologías utilizadas:

Python

Requests

Web Scraping

📌 ¿Qué aprenderás?

Cómo enviar solicitudes HTTP con Python

Cómo extraer información desde páginas web

Automatizar consultas masivas

Manejo de datos en scripts reales


*************************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 antecedentes con cedula</div>

    <div class="fila">

        <textarea style="width: 186px;height: 70px;"  id="txtIdentificador" value="" ></textarea>

       <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/Demo66.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

requests.packages.urllib3.disable_warnings()

def index(request):

    return render(request,"Demo66.html")


def procesar(request):

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

    rptaJson=[]

    try:

        acodigos=codigo.split(",")

        for cedula in acodigos:

            rptaJson.append( consultar(cedula))

    except Exception as e:

        print("Error "+ str(e))

    return JsonResponse(rptaJson,safe=False)

def consultar(cedula):

    objRpta={"cedula":cedula,"nombre":"","tieneAntecedente":"","Delidos":[],"mensaje":""}

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

    sesion=requests.session()

 req=sesion.get("https://apps.procuraduria.gov.co/webcert/inicio.aspx",headers=header,verify=False,allow_redirects=True)

    if req.status_code==200:

        html=req.text

        pos=html.find("form1")

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

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

        urlform=html[posValue+9:poscomilla]

        urlform=urlform.replace("&amp;","&")

        print(urlform)


        pos=html.find("__VIEWSTATE")

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

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

        viewsatate=html[posValue+7:poscomilla]

        #print(viewsatate)


        pos=html.find("__VIEWSTATEGENERATOR")

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

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

        viewsatategenerator=html[posValue+7:poscomilla]

        #print(viewsatategenerator)


        pos=html.find("__EVENTVALIDATION")

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

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

        eventvalidation=html[posValue+7:poscomilla]

        #print(eventvalidation)


        pos=html.find("lblPregunta")

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

        poscomilla=html.find("<",posValue+1)

        pregunta=html[posValue+1:poscomilla]

        print(pregunta)

        documento=cedula

        respuesta=""

        if pregunta=="¿ Cual es la Capital del Vallle del Cauca?":

            respuesta="cali"

        if pregunta=="¿ Cual es la Capital de Antioquia (sin tilde)?":

            respuesta="medellin"

        if pregunta=="¿ Cual es la Capital del Atlantico?":

            respuesta="barranquilla"

        if pregunta=="¿Escriba los dos ultimos digitos del documento a consultar?":

            respuesta=documento[-2:]

        if pregunta=="¿Escriba los tres primeros digitos del documento a consultar?":

            respuesta=documento[:3]

        if "Cuanto es" in pregunta:


            posValue=pregunta.find("Cuanto es")

            poscomilla=pregunta.find("?",posValue)

            print(pregunta[posValue+9:poscomilla].strip())

            try:

                respuesta=eval(pregunta[posValue+9:poscomilla].strip())

            except Exception as e:

                print("error en eval")

                respuesta=""

        print(respuesta)

        if respuesta!="":


            url="https://apps.procuraduria.gov.co/webcert"+urlform

            print(url)

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

                        "host":"apps.procuraduria.gov.co",

                        "origin":"https://apps.procuraduria.gov.co",

                        "referer":url.replace("%3d","=").replace("%2f","/"),

                        "x-microsoftajax":"Delta=true",

                        "x-requested-with":"XMLHttpRequest",

                        "content-type":"application/x-www-form-urlencoded; charset=UTF-8"}

            

            payload={"ctl05":"UpdatePanel1|btnConsultar",

                    "foo":"",

                    "ddlTipoID":"1",

                    "txtNumID":documento,

                    "txtRespuestaPregunta":respuesta,

                    "txtEmail":"",

                    "__EVENTTARGET":"",

                    "__EVENTARGUMENT":"",

                    "__VIEWSTATE":viewsatate,

                    "__VIEWSTATEGENERATOR":viewsatategenerator,

                    "__EVENTVALIDATION":eventvalidation,

                    "__ASYNCPOST":"true",

                    "btnConsultar":"Consultar"

                    }

            req=sesion.post(url,data=payload,headers=header,verify=False)

            if req.status_code==200:

                html=req.text

                pos=html.find("datosConsultado")

                if pos>-1:

                    posnombre=html.find("Señor",pos)

                    posfinnombre=html.find("identificado",posnombre)

                    htmlnombre=html[posnombre:posfinnombre]

                    

                    anombre=[]

                    pos=htmlnombre.find("<span>")

                    while pos>-1:

                        posmenor=htmlnombre.find("<",pos+6)

                        if posmenor>-1:

                            anombre.append(htmlnombre[pos+6:posmenor])

                        pos=htmlnombre.find("<span>",pos+6)

                    #print(" ".join(anombre))

                    objRpta["nombre"]=" ".join(anombre)

                    posAntecedente=html.find("SeccionAnt")

                    if posAntecedente>-1:

                        objRpta["tieneAntecedente"]="Si"

                        posDelito=html.find("Delitos",posAntecedente)

                        posinicio=html.find("Descripción del Delito",posDelito)

                        posfin=html.find("</table>",posinicio)

                        tabla=html[posinicio:posfin]

                        postd=0

                        while postd>-1:

                            postd=tabla.find("<td>",postd)

                            postdfin=tabla.find("<",postd+4)

                            if postd>-1 and postdfin>-1:

                                #print(tabla[postd+4:postdfin])

                                objRpta["Delidos"].append(tabla[postd+4:postdfin])

                            if postd==-1:

                                break

                            postd=postdfin

                    else:

                        objRpta["tieneAntecedente"]="No"

                        posh2=html.find("<h2>",posfinnombre)

                        posh2fin=html.find("</h2>",posh2)

                        #print(html[posh2+4:posh2fin])

                else:

                    objRpta["mensaje"]="no se encontro información"

        else:

            objRpta=consultar(cedula)

    return objRpta



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