2012-04-17 6 views
6

¿Cómo puedo verificar si hay valores de atributo de objeto de entrada en código HTML usando Delphi?Comprobando si hay valores de atributo de objeto <input> en el código HTML usando Delphi

there isn't value attribute. 
<input name="input1" type="text"/> 
there is value attribute. 
<input name="input1" type="text" value=""/> 

He intentado lo siguiente

if WebBrowser1.OleObject.Document.GetElementByID('input1').getAttribute('value')<>nil then 
     ShowMessage('value attribute is available') 
    else 
     ShowMessage('value attribute isn"t available') 
+5

No es posible comprobar una variante nula contra, véase 'No asignado', 'VarIsNull' 'VarIsEmpty', etc. en la documentación. –

+3

Es más complicado. Como [kobik] (http://stackoverflow.com/users/937125/kobik) señaló en nuestra discusión, tendrá que verificar el valor del atributo 'value' (suena tonto, lo sé :-), pero hay un * problema * con el atributo 'value' dado que el analizador DOM lo elimina cuando está vacío, así que de este' 'el analizador hace esto' 'por lo tanto, no puedes simplemente verificar si el atributo' value' existe de una manera común. Si el atributo 'value' tiene un valor no vacío, permanece ahí, por supuesto, pero parece que no es lo que estás preguntando. – TLama

+0

posible duplicado de [XPath en Delphi7?] (Http://stackoverflow.com/questions/517145/xpath-in-delphi7) –

Respuesta

0

pensé que me gustaría poner esto como una respuesta, ya que me tomó un tiempo para juntar algo de código para investigar lo que se dice en el comentarios a la q, y pensé que también podría compartir ese esfuerzo y los resultados, que no eran lo que había estado esperando.

Parece a partir de los resultados siguientes que no se puede decir si una etiqueta de entrada tiene un atributo de "valor" del DOM de MSHTML porque el DOM "sintetiza" uno si no está físicamente presente en el código fuente HTML. No estoy seguro de si esa era la respuesta que esperaba el OP, pero al menos le ahorraría la molestia de insertar un nuevo nodo de atributo si deseara para establecer el "valor" del elemento de entrada en el código. Si otoh, realmente necesita saber si un valor atributo está presente en la fuente, que era la q original, entonces necesita otro analizador, posiblemente laminados en casa, tal vez un analizador XML si el formato de la página es compatible con XML.

El ejemplo siguiente muestra que el DOM informa: a) la existencia de un atributo de valor incluso cuando no hay ninguno presente en el código fuente HTML (Input1); b) un atributo llamado 'valor' incluso cuando su valor de nodo está vacío (Entrada 2); y que c) Input1 y Input2 son indistinguibles entre sí en la base aplicada en la rutina DumpNode.

Dado el HTML en este DFM parcial:

object moHtml: TMemo 
    [...] 
    Lines.Strings = (
    '<html>' 
    ' <body>' 
    ' <p>This has no value attribute.' 
    ' <input name="input1" type="text"/>' 
    ' <p>This has an empty value attribute.' 
    ' <input name="input2" type="text" value=""/>' 
    ' <p>This has a value attribute.' 
    ' <input name="input3" type="text" value="already has a value"' + 
     '/>' 
    ' </body>' 
    '</html>') 

El código de abajo: informes

Node name: INPUT 
    value: 
    147: type: >text< 
    158: value: >< 
    160: name: >input1< 
Node name: INPUT 
    value: 
    147: type: >text< 
    158: value: >< 
    160: name: >input2< 
Node name: INPUT 
    value: 
    147: type: >text< 
    158: value: >already has a value< 
    160: name: >input3< 

Código:

procedure TForm1.DumpItems; 
var 
    E : IHtmlElement; 
    D : IHtmlDomNode; 

    procedure DumpNode(ANode : IHtmlDomNode); 
    var 
    Attrs : IHtmlAttributeCollection; 
    A : IHtmlDomAttribute; 
    V : OleVariant; 
    i : Integer; 
    begin 
    Log('Node name', ANode.nodeName); 
    V := ANode.nodeValue; 
    if not VarIsNull(V) and not VarIsEmpty(V) then 
     Log('  value', V) 
    else 
     Log('  value', ''); 

    Attrs := IDispatch(ANode.Attributes) as IHtmlAttributeCollection; 
    for i := 0 to Attrs.length - 1 do begin 
     V := i; 
     A := IDispatch(Attrs.item(V)) as IHtmlDomAttribute; 
     V := A.nodeValue; 
     if (CompareText(A.nodeName, 'Name') = 0) or (CompareText(A.nodeName, 'Input') = 0) or (CompareText(A.nodeName, 'Type') = 0) or (CompareText(A.nodeName, 'Value') = 0) then begin 
     if not VarIsNull(V) and not VarIsEmpty(V) then 
      Log(' ' + IntToStr(i) + ': ' + A.nodeName, '>' + V + '<') 
     else 
      Log(' ' + IntToStr(i) + ': '+ A.nodeName, '') 
     end; 
    end; 

    end; 

begin 
    D := IDispatch(WebBrowser1.OleObject.Document.GetElementByID('input1')) as IHtmlDomNode; 
    DumpNode(D); 

    D := IDispatch(WebBrowser1.OleObject.Document.GetElementByID('input2')) as IHtmlDomNode; 
    DumpNode(D); 

    D := IDispatch(WebBrowser1.OleObject.Document.GetElementByID('input3')) as IHtmlDomNode; 
    DumpNode(D); 
end; 

procedure TForm1.Log(const ALabel, AValue : String); 
begin 
    Memo1.Lines.Add(ALabel + ': ' + AValue); 
end; 

procedure TForm1.btnLoadClick(Sender: TObject); 
var 
    V : OleVariant; 
    Doc : IHtmlDocument2; 
begin 
    WebBrowser1.Navigate('about:blank'); 
    Doc := WebBrowser1.Document as IHTMLDocument2; 
    V := VarArrayCreate([0, 0], varVariant); 
    V[0] := moHtml.Lines.Text; 
    Doc.Write(PSafeArray(TVarData(v).VArray)); 
    Doc.Close; 
end; 

procedure TForm1.btnDumpClick(Sender: TObject); 
begin 
    DumpItems; 
end; 
Cuestiones relacionadas