Pascal/Turbo Pascal - Parsear contenido HTML

 
Vista:
sin imagen de perfil

Parsear contenido HTML

Publicado por Luis (4 intervenciones) el 27/07/2015 19:34:24
Buen día con todos,
Tengo una duda de hace algunos días, he rebuscado por el foro como ponerle fin a esto sin resultado.
Aquí voy,
Tengo hecho un programita el cual consulta una pagina web a partir de la inserción unos parametros de consulta y un captcha mediante POST, ingresado esto me arroja una información en tabla. Hasta aquí todo bien, pues la almaceno en una variable.
Mi problema incia al querer "discernir o procesar" esta información, necesito capturar los nombres de las columnas y el contenido de las filas, mas no traerme el código de la web. Tengo entendido que el método de solución a esto sería parsear, pero no lo eh comprendido bien, pues estos buscan etiquetas o nombres del campo, pero en mi caso la info que obtengo no se da de esa manera. Quisiera me puedan ayudar, subo mi código y la web que me traigo como resultado.
Gracias de antemano por su tiempo, saludos.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
unit leer_numeracion;
 
{$mode objfpc}{$H+}
 
interface
 
uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,fphttpclient,Process,
  ExtCtrls;
const
  {$IFDEF UNIX}
     ruta_trabajo='/tmp/';
     comando_ocr='/usr/local/bin/tesseract ';
  {$ENDIF}
  {$IFDEF WINDOWS}
     ruta_trabajo='d:\temp\';
     comando_ocr='x:\sistemas\tesseract\tesseract.bat ';
 {$ENDIF}
 
type
 
  { TForm1 }
 
TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Edit8: TEdit;
    Limpiar: TButton;
    Edit1: TEdit;         //URL CAPTCHA
    Edit2: TEdit;         //URL WEB
    Edit3: TEdit;         //CODIGO ADUANA
    Edit4: TEdit;
    Edit5: TEdit;
    Edit6: TEdit;
    Edit7: TEdit;
    Image1: TImage;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Memo1: TMemo;
    Memo2: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure LimpiarClick(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;
 
var
  Form1: TForm1;
  codigo_captcha,coco:string;       //VARIABLES GLOBALES
 
implementation
 
{$R *.lfm}
 
{ TForm1 }
 
procedure TForm1.Button1Click(Sender: TObject); // INICIO BOTON CAPTCHA
var
  httpz:TFPHTTPClient;
  data1:TMemoryStream;
  nombre_img,nombre_txt,url_captcha:string;
  cade:string;
  comando:string;
  proceso:Tprocess;
  Captcha1:Tstringlist;
  begin
   //TEXTO
   nombre_txt:='TC';
   nombre_txt:='d:\'+nombre_txt+formatdatetime('YYYY_MM_DD_hhnnss',now);
   //IMAGEN
   nombre_img:='IC';
   nombre_img:='d:\'+nombre_img+formatdatetime('YYYY_MM_DD_hhnnss',now)+'.jpg';
   data1:=Tmemorystream.Create;
   httpz:=TFPHTTPClient.Create(nil);
   httpz.AddHeader('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36');
   url_captcha:=edit1.text ; //OBTIENE URL CAPTCHA
   try
      httpz.Get(url_captcha,data1);  // OBTIENE EL CAPTCHA DE URL Y LA ALMACEA EN DATA1
      data1.SaveToFile(nombre_img);  // GRABA IMAGEN
      coco:=httpz.Cookies.Text;      // ALMACENA LA COOKIE
      memo2.Text:=coco;              // MUESTRA LA COOKIE
      image1.Picture.LoadFromFile(nombre_img);  // CARGA IMAGEN EN FORMULARIO
   finally
      data1.Free;
      httpz.free;
   end;
   comando:=comando_ocr+nombre_img+' '+nombre_txt+' -psm 8 letters';  // LINEA DE COMANDO
 try
    Proceso := TProcess.Create(nil);
    Proceso.CommandLine:=comando;
 {$IFDEF UNIX}
 proceso.Environment.Add('TESSDATA_PREFIX=/usr/local/share');
 {$ENDIF}
// Proceso.Options := Proceso.Options + [poWaitOnExit, poStderrToOutPut,poUsePipes];
   Proceso.Options := Proceso.Options + [poWaitOnExit,poUsePipes];
   Proceso.ShowWindow:=swoHIDE;
   Proceso.Execute;
except on e:Exception do
   showmessage('error:'+e.message);
end;
   Captcha1:=tstringlist.Create;
   cade:='';
 if fileexists(nombre_txt+'.txt') then
    begin
      Captcha1.LoadFromFile(nombre_txt+'.txt'); // CARGA TXT Y LEE
      cade:=Captcha1.text;                      // ALMACENA SU VALOR EN CADE
      codigo_captcha:=cade;
      edit7.text:=cade;                         // MUESTRA EL VALOR DE CADE EN CAMPO
    end;
end; //FIN BOTON CAPTCHA  
 
procedure TForm1.Button2Click(Sender: TObject);    //INICIO BOTON WEB
  var
    http2:TFPHTTPClient;
    data2:Tstringstream;
    cadena:string;
    url_web,cod_aduana:string;
  begin
    url_web:=Edit2.Text;// OBTIENE URL WEB
    cod_aduana:=Edit3.Text;
    // CADENA POST
    cadena:='valueCmbOpe=&valueRegimen=10&CG_cadu='+cod_aduana+'&tipusua=1&CG_cage=0659&cg_creg=10&cGcop  Manif=00&cGcopDuim=00&cGcopManifEER=00&codigo='+codigo_captcha+'&cG_fecha=&cG_fano=&cG_norden=';
    http2:=TFPHTTPClient.Create(nil);
    http2.AddHeader('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36');
    http2.AddHeader('Connection', 'keep-alive');
    data2:=Tstringstream.Create('');
    http2.Cookies.Text:=coco;
    http2.RequestHeaders.Add('application/x-www-form-urlencoded');
    http2.AddHeader('Connection', 'keep-alive');
  try
    http2.FormPost(url_web,cadena,data2); // URL, CADENA , RESPUESTA
    //DATA2 CONTIENE RESULTADO DE WEB HTML
  Memo1.Text:=data2.DataString; // MOSTRANDO RESPUESTA HTML
  //¿PARSEAR CONTENIDO DE DATA2?  
  finally
    data2.Free;
    http2.Free;
  end;
end; // FIN BOTON WEB

Aquí código HTML resultado

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CONSULTA DE ENVIOS DE TELEDESPACHO</title>
<script language="javascript" src="/aduanas/js/diseno.js"></script>
<script language=javascript>document.write(cab_pag("CONSULTA DE ENVIOS DE TELEDESPACHO"))</script>
<script language='javascript' src='/aduanas/js/libpopup.js'></script>
<style type='text/css'><!--
    .hand {cursor: hand;}
    .detalle {	font-family: Verdana, Arial, Helvetica, sans-serif;	font-size: 9px;
     	font-style: normal;	font-weight: normal;	color: #000000;}
    -->
</style>
</head>
<body>
    <TABLE WIDTH='100%'  border font-size: x-small>
 
     <TR VALIGN=top>
	  <TD WIDTH='4%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>
       <a  class='hand' onMouseOut='kill()' onMouseOver="popup('<span class=detalle ><p>T:CORREO TCI<BR>P:MAILWARE ADUANAS<BR>S:MAILWARE ASOCIACION DE AGENTES<BR>M:MAILWARE COURIER ADUANAS<BR>I:CORREO INTERNET<BR>C:CORREO CORPORATIVO<BR>D:CORREO USANDO DISKETTE<BR>W:TELEDESPACHO WEB<BR></p></span>','#FFFFCC','T')">Correo</a></B></p></CENTER></font></TD>
	   <TD WIDTH='6%' BGCOLOR='e1e1e1'><font size=1><P><CENTER><B>Orden </B></CENTER></P></font></TD>
	   <TD WIDTH='7%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Fecha </B></P></CENTER></font></TD>
	   <TD WIDTH='7%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Hora </B></P></CENTER></font></TD>
	   <TD WIDTH='8%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Archivo </B></P></CENTER></font></TD>
	   <TD WIDTH='7%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Declarac.</B></p></CENTER></font></TD>
     <TD WIDTH='6%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Serie</B></p></CENTER></font></TD>
	   <TD WIDTH='6%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Item</B></p></CENTER></font></TD>
	   <TD WIDTH='6%'  BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Tipo Trans/Env&iacute;o</B></p></CENTER></font></TD>
	   <TD WIDTH='10%' BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Gu&iacute;a Postal</B></p></CENTER></font></TD>
	   <TD WIDTH='30%' BGCOLOR='e1e1e1'><font size=1><CENTER><P><B>Observaci&oacute;n</B></p></CENTER></font></TD>
	 </TR>
 
          <TR bgcolor='#FFFFFF'>
               <td align="center"><font size=2>W</font></td>
 			   <td align="center"><font size=2>003797</font></td>
               <td align="center"><font size=2>17/07/2015</font></td>
               <td align="center"><font size=2>15:01:30</font></td>
 
               	<td align="center"><font size=2>00920709&nbsp;</font></td>
 
               <td align="center">
                ------
 
               </td>
               <td align="center"><font size=2>------</font></td>
               <td align="center"><font size=2>------</font></td>
               <td align="center">
                 <font size=2>05
 
                </font>&nbsp;
               </td>
               <td align="center"><font size=2>------</font></td>
               <td>
               9074 :  &nbsp; ( Advertencia de Rectificación ) &nbsp;SECUP:1 BDUAHDR1.Codi_Prove:<br> ** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CODIGO DE PROVEEDOR EXTRANJERO NO EXISTE, VERIFICAR EN EL PORTAL ADUANERO</br>
 
              </td>
          </TR>
 
          <TR bgcolor='#FFFFFF'>
               <td align="center"><font size=2>W</font></td>
 			   <td align="center"><font size=2>003797</font></td>
               <td align="center"><font size=2>17/07/2015</font></td>
               <td align="center"><font size=2>15:01:41</font></td>
 
               	<td align="center"><font size=2>00920709&nbsp;</font></td>
 
               <td align="center">
                ------
 
               </td>
               <td align="center"><font size=2>------</font></td>
               <td align="center"><font size=2>------</font></td>
               <td align="center">
                 <font size=2>05
 
                </font>&nbsp;
               </td>
               <td align="center"><font size=2>------</font></td>
               <td>
               9204 :  &nbsp; ( Advertencia de Rectificación ) &nbsp;DUAHDR.DIRE_IMPOR-20508565934-dirección diferente al registrado<br> ** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MODIFICACIÓN IMPROCEDENTE, NO SERÁ CONSIDERADA</br>
 
              </td>
          </TR>
 
</body>
</html>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Parsear contenido HTML

Publicado por ramon (2158 intervenciones) el 07/08/2015 19:24:03
Te recomiendo lo pases a la sección de free pascal puesto que es el que presentas.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Parsear contenido HTML

Publicado por Luis (4 intervenciones) el 08/08/2015 00:39:33
Si existiera, la hubiera publicado ahí. Solo veo esta y la delphi.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Parsear contenido HTML

Publicado por ramon (2158 intervenciones) el 08/08/2015 11:54:48
Disculpa no avía entrado es el sitio.
Explícame lo que te pasa y intentare ayudarte de momento te diré que tu unidad me da 3 errores de compilación.
Pero tu me pasas un código de resultado.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Parsear contenido HTML

Publicado por Luis (4 intervenciones) el 10/08/2015 16:37:06
No te preocupes,
El error se debe ha que hay que modificar la librería fphttpclient, la ruta es "codetyphon\fpcsrc\packages\fcl-web\src\base\fphttpclient.pp" uso la versión v5.3 de typhon.
Debes comentar las siguientes líneas: 644,645.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function TFPCustomHTTPClient.ReadResponseHeaders: integer;
 
  Procedure DoCookies(S : String);
 
  Var
    P : Integer;
    C : String;
 
  begin
    //If Assigned(FCookies) then     //COMENTADO POR MI
     //FCookies.Clear;               //COMENTADO POR MI
    P:=Pos(':',S);
    System.Delete(S,1,P);
    Repeat
      P:=Pos(';',S);
      If (P=0) then
        P:=Length(S)+1;
      C:=Trim(Copy(S,1,P-1));
      Cookies.Add(C);
      System.Delete(S,1,P);
    Until (S='');
  end;

Te adjunto la fuente de mi proyecto y la librería modificada, he avanzado algo. Hice una forma de eliminar todo el contenido del HTML con un procedimiento, sé que no es la mejor forma, porque si varía o añaden algo mas en la web tendría que modificar mi fuente, pero a no tener ayuda decidí hacer algo. Si logras la forma de parsear y me explicas te lo agradecería mucho. Con lo hecho hasta ahora, verás que al lanzar el programa captura la data, pero necesito ahora esos valores ingresarlos a una BD, interpretando un salto de linea como el final para así pasar al siguiente campo en BD.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Parsear contenido HTML

Publicado por ramon (2158 intervenciones) el 12/08/2015 17:37:20
//If Assigned(FCookies) then //COMENTADO POR MI { function que detecta si el fcookies esta vació o tiene datas}
//FCookies.Clear; //COMENTADO POR MI {En caso de taner datos los borra}

como podrás ver fcookies es un tstring.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Parsear contenido HTML

Publicado por ramon (2158 intervenciones) el 12/08/2015 18:07:11
esta es su estructura {function Assigned(P: Pointer):Boolean;}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Parsear contenido HTML

Publicado por Luis (4 intervenciones) el 12/08/2015 19:42:08
Como bien claro dices tú,
FCookies.Clear
limpiaba la cookies que obtenía, por ende no podría luego pasarlas. Comentandolo como hice funcionó.
Levantaste mi código que adjunte?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Parsear contenido HTML

Publicado por ramon (2158 intervenciones) el 12/08/2015 22:58:10
Su pongo te refieres si lo baje si.

Referente al código If Assigned(FCookies) then con poner lo así serbia If not Assigned(FCookies) then
si lo que deseabas era no limpiar.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar