2

如何通过标签和特定属性找到元素?我编写的这段代码确实通过它的标签找到了它,但是它似乎无法通过它的属性找到它。

为什么这段代码会有这样的行为?

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;
4

1 回答 1

1
E := Collection.item(i, EmptyParam) as IHTMLElement;
// you should clear the value of matched attributes counter for each element
Count := 0;
for j := 0 to Attributes.Count-1 do
  begin

PS 一点优化:

if not VarIsNull(E.getAttribute(FAttributeName,0)) then
begin
  if (E.getAttribute(FAttributeName,0)=FAttributeValue) then
  Inc(Count,1);
end else 
  // if any of attributes of element is not found, you can skip to next element.
  break;
于 2013-08-22T15:10:08.437 回答