gpt4 book ai didi

delphi - 按属性查找元素

转载 作者:行者123 更新时间:2023-12-02 10:56:08 24 4
gpt4 key购买 nike

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

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

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;

最佳答案

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

附注一点优化:

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;

关于delphi - 按属性查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com