Delphi 10.3-比较IHTMlements

Delphi 10.3-比较IHTMlements,delphi,xpath,compare,Delphi,Xpath,Compare,我正在尝试为在TWebBrowser内的网站上单击(例如)的元素构建XPath。 如果你知道一些可用的函数或其他方法,请给我一个提示 procedure TForm1.Button2Click(Sender: TObject); var Elem: IHTMLElement; ss: string; ii: Integer; function GetElemOrder(e: IHTMLElement): integer; var jj: Integer; ee:

我正在尝试为在TWebBrowser内的网站上单击(例如)的元素构建XPath。 如果你知道一些可用的函数或其他方法,请给我一个提示

procedure TForm1.Button2Click(Sender: TObject);
var
  Elem: IHTMLElement;
  ss: string;
  ii: Integer;
 function GetElemOrder(e: IHTMLElement): integer;
  var
    jj: Integer;
    ee: IHTMLElement;
    Coll: IHTMLElementCollection;
  begin
    //get all children of the elem parent - the elem is a child itself
    Coll := e.parentElement.children as IHTMLElementCollection;
    //filter the tags to minimize the list (only the same tags as the elem)
    Coll := Coll.tags(e.tagName) as IHTMLElementCollection;
    for jj := 0 to Coll.length - 1 do begin
      inc(Result);
      ee := Coll.item(jj, EmptyParam) as IHTMLElement;
      //go through the list and check if the elem was found
      if (e = ee) then  // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< this doesn't work
        //return the actual count
        Exit;
    end;
    Result := 0; // result 0 means always an error, as the elem wasn't found in the collection
  end;

begin
  //get element obj
  Elem := GetElementById(wb.Document, 'input_username') as IHTMLElement;
  if Assigned(Elem) then
    //build the xpath until reach the root
    while elem.parentElement <> nil do begin
      // get the order of the elem in the list of children e.g. 3rd DIV from 5 DIVs
      ii := GetElemOrder(Elem);
      ss := '/' + Elem.tagName + '[' + ii.ToString + ']' + ss;
      //go to the next level
      Elem := Elem.parentElement;
    end;
end;
procedure TForm1.按钮2点击(发送方:TObject);
变量
要素:IHTMlement;
ss:字符串;
ii:整数;
函数GetElemOrder(e:ihtmlement):整数;
变量
jj:整数;
ee:ihtmlement;
Coll:IHTMLElementCollection;
开始
//获取elem父级的所有子级-elem本身就是一个子级
Coll:=e.parentElement.children作为IHTMlementCollection;
//过滤标记以最小化列表(仅与元素相同的标记)
Coll:=Coll.tags(e.tagName)作为IHTMlementCollection;
对于jj:=0到Coll.length-1不开始
公司(结果);
ee:=符合IHT规定的集合项(jj,清空参数);
//查看列表并检查是否找到元素

如果(e=ee),则在尝试
Inc()
之前,//
GetElemOrder()
未初始化
Result
<代码>结果
不会自动初始化为0,您必须明确地执行此操作。看见在这种情况下,考虑使用<代码>退出(JJ + 1);<代码>相反,根据:“从Delphi 2009开始,
Exit
可以接受一个指定结果的参数。该参数必须与函数结果的类型相同。”测试两个COM接口指针是否引用内存中的同一对象的正确方法是在比较它们之前将它们转换为
IUnknown
,即
if(e as IUnknown)=(ee as IUnknown)
。非常感谢@RemyLebeau!它现在可以正常工作了!将完成“result”的初始化,不知道为什么这里没有。很好地指向文档!如果您使用
Exit(…);
而不是
Exit;
,那么您根本不需要初始化
result
,更不用说
Inc()
在每次循环迭代中使用它。
函数GetElemOrder(e:ihtmlement):integer;…开始jj:=0到Coll.length-1如果(…)退出(jj+1);…结束;…退出(0);结束;