如何在TMS WEB Core中遍历含指定类名的所有HTML元素
用纯Delphi代码遍历DOM中动态创建的TestingClass元素
要实现纯Delphi代码遍历DOM中动态生成的带TestingClass类的元素,你可以通过浏览器组件的COM DOM接口来完成,无需内嵌JavaScript。以下是具体代码(假设你使用TWebBrowser组件):
uses MSHTML, SHDocVw; procedure TfrmMain.Testing(Sender: TObject); var HTMLDoc: IHTMLDocument2; Elements: IHTMLElementCollection; Element: IHTMLElement; I: Integer; begin // 获取当前页面的DOM文档对象 if not Assigned(WebBrowser1.Document) then Exit; if not WebBrowser1.Document.QueryInterface(IHTMLDocument2, HTMLDoc) then Exit; // 调用querySelectorAll获取所有带TestingClass类的元素 Elements := HTMLDoc.querySelectorAll('.TestingClass') as IHTMLElementCollection; // 遍历所有找到的元素 for I := 0 to Elements.length - 1 do begin Element := Elements.item(I, EmptyParam) as IHTMLElement; // 这里可对Element进行操作,比如输出标签名到调试窗口 OutputDebugString(PChar('找到元素: ' + Element.tagName)); // 按需访问Element的属性、内容等 end; end;
关键说明
- 先获取
IHTMLDocument2接口,这是Delphi操作HTML DOM的核心接口之一 querySelectorAll('.TestingClass')和你之前用JavaScript的逻辑完全一致,返回所有匹配选择器的元素集合- 遍历
IHTMLElementCollection集合时,通过item方法逐个获取元素,再转换为IHTMLElement进行后续操作
内容的提问来源于stack exchange,提问作者Shaun Roselt
相关产品推荐
相关产品推荐

