1
+ /*
2
+ Demostración de Web Scraping con Javascript y Expresiones Regulares.
3
+ Autor: Julio J. - @jjyepez
4
+ Fecha: 24/06/2018
5
+ */
6
+
7
+ // --- si quieres probar con otros criterios de filtrado, remplaza la URL obtenida en ML en la sig linea --- jjy
8
+ const urlML = "https://videojuegos.mercadolibre.com.co/juego-ps4_Envio_Gratis_DisplayType_LF_OrderId_PRICE*DESC_Discount_40-100"
9
+
10
+ iniciar ( )
11
+
12
+ function iniciar ( ) {
13
+ traerHTML ( urlML )
14
+ actualizarFecha ( )
15
+ }
16
+
17
+ function traerHTML ( urlML ) {
18
+ // --- servicio propio para superar restricciones CORS ... by jjyepez
19
+ const URL = "https://noesishosting.com/sw/cors/?a=cors&url=" + urlML
20
+
21
+ // --- traer el HTML del sitio web
22
+ fetch ( URL )
23
+ . then ( rsp => rsp . text ( ) )
24
+ . then ( rslt => {
25
+ const jsonDatosExtraidos = procesarResultados ( rslt )
26
+ renderDatosExtraidos ( jsonDatosExtraidos )
27
+ } )
28
+ . catch ( err => { console . log ( err ) } )
29
+ }
30
+
31
+ // --- procesar con RegExp
32
+ function procesarResultados ( html ) {
33
+ const jsonDatos = [ ]
34
+ var matches = null
35
+
36
+ // --- RegExp by jjyepez
37
+ const expresionRegular = new RegExp (
38
+ "<img(?:.*?)alt=\'(.*?)\'(?:.*?)src=\'(.*?)\'(?:.*?)<a(?:.*?)href=\"(.*?)\"(?:.*?)<del>(.*?)</del>(?:.*?)fraction\">(.*?)</span>?(?:.*?)discount(?:.*?)>(.*?\%)"
39
+ , "g" )
40
+
41
+ do {
42
+ // --- extrayendo datos
43
+ matches = expresionRegular . exec ( html )
44
+ jsonDatos . push ( matches )
45
+
46
+ }
47
+ while ( matches !== null )
48
+ return jsonDatos
49
+ }
50
+
51
+ function renderDatosExtraidos ( datos ) {
52
+ const $divResultados = document . getElementById ( 'resultados' )
53
+ $divResultados . innerHTML = ''
54
+ datos . forEach ( reg => {
55
+ if ( reg ) {
56
+ const $card = document . createElement ( 'div' )
57
+ $card . classList . add ( 'card' )
58
+ $card . addEventListener ( 'click' , ( ) => {
59
+ window . open ( reg [ 3 ] )
60
+ } )
61
+ $card . innerHTML = `
62
+ <div class="thumb" >
63
+ <img src="${ reg [ 2 ] } "/>
64
+ </div>
65
+ <div class="titulo">${ reg [ 1 ] } </div>
66
+ <div class="precio-ant">
67
+ <div class="precio">${ reg [ 4 ] } </div>
68
+ <div class="dcto" >-${ reg [ 6 ] } OFF</div>
69
+ </div>
70
+ <div class="oferta">$ ${ reg [ 5 ] } </div>
71
+ `
72
+ $divResultados . appendChild ( $card )
73
+ }
74
+ } )
75
+ }
76
+
77
+ function actualizarFecha ( ) {
78
+ const hoy = new Date ( )
79
+ const $fecha = document . getElementById ( 'fecha' )
80
+ $fecha . innerHTML = `Actualizado al: ${ ( '0' + hoy . getDate ( ) ) . substr ( - 2 ) } /${ ( '0' + ( hoy . getMonth ( ) + 1 ) ) . substr ( - 2 ) } /${ hoy . getFullYear ( ) } `
81
+ }
0 commit comments