2
Comment trouver un élément par son tag et par des attributs spécifiques? Ce code que j'ai écrit le trouve par son tag, mais il ne semble pas le trouver par ses attributs.Rechercher un élément par attribut
Pourquoi un tel comportement existe-t-il avec ce code?
function FindElement(const Tag:String; const Attributes:TStringList):IHTMLElement;
var
FAttributeName, FAttributeValue:String;
Collection: IHTMLElementCollection;
E:IHTMLElement;
Count:Integer;
i, j:Integer;
begin
Collection := (EmbeddedWB1.Document as IHTMLDocument3).getElementsByTagName(Tag);
for i := 0 to Pred(Collection.length) do
begin
E := Collection.item(i, EmptyParam) as IHTMLElement;
for j := 0 to Attributes.Count-1 do
begin
FAttributeName:=LowerCase(List(Attributes,j,0,','));
FAttributeValue:=LowerCase(List(Attributes,j,1,','));
if not VarIsNull(E.getAttribute(FAttributeName,0)) then
begin
if (E.getAttribute(FAttributeName,0)=FAttributeValue) then
Inc(Count,1);
end;
if Count = Attributes.Count then
Exit(E);
end;
end;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
Attributes:TStringList;
begin
Attributes:=TStringList.Create;
Attributes.Add('id,something');
Attributes.Add('class,something');
FindElement('sometag',Attributes);
Attributes.Free;
end;
problème ce code ne sera pas obtenir attribut pour certains éléments .. tels que '' –
Certains attributs, comme 'class', ont leur propre propriété séparée , donc il est possible que 'getAttribute()' les filtre. –
Une autre optimisation consiste à appeler 'getAttribute()' une seule fois et à mettre en cache son résultat dans une variable locale, puis vous pouvez l'utiliser autant de fois que vous le souhaitez. –