Scraping consulta RUC (Ecuador)

 El código utilizado para hacer el scraping es el siguiente el proyecto esta desarrollado con Django python:

como guía pyueden ver el video en https://www.youtube.com/watch?v=GOy6H9in5zw

**********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">Scrapping Consulta RUC (Ecuador)</div>

    <div class="fila">

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

       <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/Demo12.js' %}" ></script>

</body>

</html>

**********JAVASCRIPT**************

window.onload=function(){

    let btnProcesar=document.getElementById("btnProcesar");

    btnProcesar.onclick=function(){

        let txtIdentificador=document.getElementById("txtIdentificador").value;

        let fd=new FormData();

        fd.append("data",txtIdentificador)

        servidor({url:"procesar2",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);

    });

}

********** DJANGO VIEW **************
Instalar las siguientes dependencias
-easyocr
-requests
-python-opencv

from django.shortcuts import render
from django.http.response import HttpResponse,JsonResponse
import  urllib.request as req
import json
import requests
import easyocr
from django.conf import settings
import os
import cv2

# Create your views here.
tokenGlobal=""
def index(request):

    return render(request,"Demo12.html")

def procesar(request):

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

    rptaJson=None
    print("buscar ruc"+ruc)
    try:

        headers={"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",
                "sec-ch-ua-platform":"\"Windows\"",
                "host":"appscvsgen.supercias.gob.ec"}

        sesion=requests.Session()

        _req=sesion.get("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf",headers=headers)

        html=_req.text
        print("inicio ")
        indiceView=html.find("j_id1:javax.faces.ViewState:0")
        if(indiceView>-1):
            indexValueInicio=html.find("value=",indiceView)
            indexValueFin=html.find("\"",indexValueInicio+7)
            view=html[indexValueInicio+7:indexValueFin]
            view=view.replace(":","%3A")


        dtSesion=sesion.cookies.get_dict()

        print("Cambiar a busqueda ruc")

        headers={"content-type":"application/x-www-form-urlencoded; charset=UTF-8",
                "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",
                "sec-ch-ua-platform":"\"Windows\"",
                #"faces-request":"partial/ajax",
                "host":"appscvsgen.supercias.gob.ec",
                "cookie":"JSESSIONID="+dtSesion["JSESSIONID"],
                "referer":"https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf"}

        payload="javax.faces.partial.ajax=true&javax.faces.source=frmBusquedaCompanias%3AtipoBusqueda&javax.faces.partial.execute=frmBusquedaCompanias%3AtipoBusqueda&javax.faces.partial.render=frmBusquedaCompanias%3AparametroBusqueda+frmBusquedaCompanias%3ApanelCompaniaSeleccionada+frmBusquedaCompanias%3ApanelCaptcha+frmBusquedaCompanias%3AbtnConsultarCompania&javax.faces.behavior.event=valueChange&javax.faces.partial.event=change&frmBusquedaCompanias%3AtipoBusqueda=2&javax.faces.ViewState="+view
        _req=sesion.post("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf",data=payload,headers=headers)


        payload="javax.faces.partial.ajax=true&javax.faces.source=frmBusquedaCompanias%3AparametroBusqueda&javax.faces.partial.execute=frmBusquedaCompanias%3AparametroBusqueda&javax.faces.partial.render=frmBusquedaCompanias%3AparametroBusqueda&frmBusquedaCompanias%3AparametroBusqueda=frmBusquedaCompanias%3AparametroBusqueda&frmBusquedaCompanias%3AparametroBusqueda_query="+ruc+"&frmBusquedaCompanias=frmBusquedaCompanias&frmBusquedaCompanias%3AtipoBusqueda=2&frmBusquedaCompanias%3AparametroBusqueda_input="+ruc+"&frmBusquedaCompanias%3Abrowser=Chrome&frmBusquedaCompanias%3AaltoBrowser=372&frmBusquedaCompanias%3AanchoBrowser=1536&frmBusquedaCompanias%3AmenuDispositivoMovil=hidden&javax.faces.ViewState="+view
        _req=sesion.post("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf",data=payload,headers=headers)

        html=_req.text

        indiceNombre=html.find("data-item-value=")
        id_nombre=""
        if(indiceNombre>-1):
            indexValueFin=html.find("\"",indiceNombre+17)
            id_nombre=html[indiceNombre+17:indexValueFin]
            id_nombre=id_nombre.replace(" ","+")
            #print(id_nombre)



        payload="javax.faces.partial.ajax=true&javax.faces.source=frmBusquedaCompanias%3AparametroBusqueda&javax.faces.partial.execute=frmBusquedaCompanias%3AparametroBusqueda&javax.faces.partial.render=frmBusquedaCompanias%3AparametroBusqueda+frmBusquedaCompanias%3ApanelCompaniaSeleccionada+frmBusquedaCompanias%3ApanelCaptcha+frmBusquedaCompanias%3AbtnConsultarCompania&javax.faces.behavior.event=itemSelect&javax.faces.partial.event=itemSelect&frmBusquedaCompanias%3AparametroBusqueda_itemSelect="+id_nombre+"&frmBusquedaCompanias%3AparametroBusqueda_input="+id_nombre+"&javax.faces.ViewState="+view
        _req=sesion.post("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf",data=payload,headers=headers)

        html=_req.text
        indicesrc=html.find("src=")
        if(indicesrc>-1):
            indexValueFin=html.find("\"",indicesrc+5)
            imgcaptcha=html[indicesrc+5:indexValueFin]

            urlimge="https://appscvsgen.supercias.gob.ec"+imgcaptcha
            print(urlimge)
            _reqimg=sesion.get(urlimge,headers=headers)

            buffer=_reqimg.content
            rutaimg=os.path.join(settings.BASE_DIR,"Demo12/img/imgtemp.png")

            with open(rutaimg,"wb") as f:
                f.write(buffer)
            if os.path.isfile(rutaimg):
                print("procesando imagen")
                gray=cv2.imread(rutaimg,0)
                thresholded = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
                reader = easyocr.Reader(['en'])
                result=reader.readtext(thresholded, detail = 0, paragraph=True)
                
                captcha=result[0].replace(" ","")
                print(captcha)
                payload="javax.faces.partial.ajax=true&javax.faces.source=frmBusquedaCompanias%3AbtnConsultarCompania&javax.faces.partial.execute=frmBusquedaCompanias%3AbtnConsultarCompania+frmBusquedaCompanias%3Acaptcha+frmBusquedaCompanias%3Abrowser+frmBusquedaCompanias%3AaltoBrowser+frmBusquedaCompanias%3AanchoBrowser+frmBusquedaCompanias%3AmenuDispositivoMovil&frmBusquedaCompanias%3AbtnConsultarCompania=frmBusquedaCompanias%3AbtnConsultarCompania&frmBusquedaCompanias%3Acaptcha="+captcha+"&frmBusquedaCompanias%3Abrowser=Chrome&frmBusquedaCompanias%3AaltoBrowser=614&frmBusquedaCompanias%3AanchoBrowser=1536&frmBusquedaCompanias%3AmenuDispositivoMovil=hidden&javax.faces.ViewState="+view
                _req=sesion.post("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/busquedaCompanias.jsf",data=payload,headers=headers,allow_redirects=True)
                print(_req.text)
                if(_req.status_code==200):
                    print("*"*10)
                    _req=sesion.get("https://appscvsgen.supercias.gob.ec/consultaCompanias/societario/informacionCompanias.jsf",headers=headers,allow_redirects=True)
                    rptaJson=procesarInformacion(_req.text)



    except Exception as e:
        print("Error "+ str(e))
    

    return JsonResponse(rptaJson,safe=False)


def procesarInformacion(html):

    dtEmpres={}
    posInicio=html.find("barra.png")
    if posInicio>-1:
        posvalue=html.find(">",posInicio)
        posvalueFin=html.find("<",posvalue+1)
        dtEmpres["Nombre"]=html[posvalue+1:posvalueFin].strip()  
    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt121")
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Expediente"]=html[posvalue+7:posvalueFin]
    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt126",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["RUC"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt131",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["FechaConstitucion"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt136",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Nacionalidad"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt141",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["PlazoSocial"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt146",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["OficinaControl"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt146",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["OficinaControl"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt151",posInicio)
    if posInicio>-1:
        posvalue=html.find(">",posInicio)
        posvalueFin=html.find("<",posvalue+1)
        dtEmpres["TipoConpania"]=html[posvalue+1:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt156",posInicio)
    if posInicio>-1:
        posvalue=html.find(">",posInicio)
        posvalueFin=html.find("<",posvalue+1)
        dtEmpres["situacionLegal"]=html[posvalue+1:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt167",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Provincia"]=html[posvalue+7:posvalueFin].strip() 

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt172",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Canton"]=html[posvalue+7:posvalueFin].strip() 

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt177",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Ciudad"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt182",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Parroquia"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt187",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Calle"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt192",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Numero"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt197",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Interseccion"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt202",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Ciudadela"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt207",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Conjunto"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt242",posInicio)
    if posInicio>-1:
        posvalue=html.find("value=",posInicio)
        posvalueFin=html.find("\"",posvalue+7)
        dtEmpres["Referencia"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt253",posInicio)
    dtEmpres["CasilleroPostal"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["CasilleroPostal"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt258",posInicio)
    dtEmpres["Celular"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["Celular"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt263",posInicio)
    dtEmpres["Telefono1"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["Telefono1"]=html[posvalue+7:posvalueFin].strip()

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt268",posInicio)
    dtEmpres["Telefono2"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["Telefono2"]=html[posvalue+7:posvalueFin]

    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt273",posInicio)
    dtEmpres["SitioWeb"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["SitioWeb"]=html[posvalue+7:posvalueFin]
    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt278",posInicio)
    dtEmpres["Correo1"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["Correo1"]=html[posvalue+7:posvalueFin]
    posInicio=html.find("frmInformacionCompanias:j_idt110:j_idt283",posInicio)
    dtEmpres["Correo2"]=""
    if posInicio>-1:
        posvalue=html.find("/>",posInicio)
        temp=html[posInicio:posvalue]
        posvaluetemp=temp.find("value=")
        if posvaluetemp>-1:
            posvalue=html.find("value=",posInicio)
            posvalueFin=html.find("\"",posvalue+7)
            dtEmpres["Correo2"]=html[posvalue+7:posvalueFin]
    return dtEmpres

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