按属性查找元素

时间:2013-08-22 14:49:21

标签: delphi browser mshtml

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

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

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;

1 个答案:

答案 0 :(得分: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

<强> P.S。 一点优化:

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;
相关问题