Automatizando precios del Mercado Mayorista de Lima (EMMSA) con Python | Scraping + API
En este video te muestro cómo crear una API en Python usando scraping con datos reales del Mercado Mayorista de Lima.
************************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 precios de verduras y frutas (EMMSA)</div>
<div class="fila">
<input type="date" 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/Demo46.js' %}" ></script>
</body>
</html>
************************JAVASCRIPT**********************
window.onload=function(){
let btnProcesar=document.getElementById("btnProcesar");
btnProcesar.onclick=function(){
let txtFecha=document.getElementById("txtIdentificador").value;
let afecha=txtFecha.split("-")
let fd=new FormData();
fd.append("data",[afecha[2],afecha[1],afecha[0]].join("/"));
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
import requests
def index(request):
return render(request,"Demo46.html")
def procesar(request):
fecha=request.POST.get("data")
rptaJson={}
print("buscar fecha "+fecha)
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",
"referer":"https://www.google.com/",
"host":"www.emmsa.com.pe"
}
sesion=requests.session()
req=sesion.get("https://www.emmsa.com.pe/index.php/precios-diarios/",headers=header,verify=False)
if req.status_code==200:
html=req.text
header["referer"]="https://old.emmsa.com.pe/emmsa_spv/rpEstadistica/rpt_precios-diarios-web.php"
header["host"]="old.emmsa.com.pe"
header["content-type"]="application/x-www-form-urlencoded; charset=UTF-8"
header["origin"]="https://old.emmsa.com.pe"
payload="vid_tipo=1&vprod=&vvari=&vfecha="+fecha
req=sesion.post("https://old.emmsa.com.pe/emmsa_spv/app/reportes/ajax/rpt07_gettable_new_web.php",data=payload,headers=header,verify=False)
if req.status_code==200:
html=req.text
postbody=html.find("<tbody>")
if postbody>-1:
posfintbody=html.find("</tbody>",postbody)
tabla=html[postbody:posfintbody]
postr=0
while True:
postr=tabla.find("<tr>",postr)
if postr==-1:
break
postd=tabla.find("<td>",postr)
posmenor=tabla.find("<",postd+4)
producto=tabla[postd+4:posmenor].strip()
postd=tabla.find("<td>",posmenor)
posmenor=tabla.find("<",postd+4)
variedad=tabla[postd+4:posmenor].strip()
postd=tabla.find("<td>",posmenor)
posmenor=tabla.find("<",postd+4)
preciomin=tabla[postd+4:posmenor]
postd=tabla.find("<td>",posmenor)
posmenor=tabla.find("<",postd+4)
preciomax=tabla[postd+4:posmenor]
postd=tabla.find("<td>",posmenor)
posmenor=tabla.find("<",postd+4)
promedio=tabla[postd+4:posmenor]
rptaJson.setdefault(producto, [])
rptaJson[producto].append({"variedad":variedad,
"preciomin":float(preciomin),
"preciomax":float(preciomax),
"promedio":float(promedio)})
postr=postr+4
except Exception as e:
print("Error "+ str(e))
return JsonResponse(rptaJson,safe=False)
Comentarios
Publicar un comentario