伙计们:我在object-pascal编程中遇到了“如何获取由多个IHTMLElements组成的IHTMLElementCollection obj”的问题,我的代码如下:
function TExDomUtils.GetElementsByClassName(vDoc:IHTMLDocument3; strClassName:string):IHTMLElementCollection;
var
vElementsAll : IHTMLElementCollection;
vElementsRet : IHTMLElementCollection;
vElement : IHTMLElement;
docTmp : IHTMLDocument2;
I ,J: Integer;
begin
J := 0;
vElementsAll := vDoc.getElementsByTagName('*');
for I:=0 to vElementsAll.length - 1 do
begin
vElement := vElementsAll.item(I,0) as IHTMLElement;
if vElement.getAttribute('class',0) = strClassName then
begin
// how to get an IHTMLElementCollection obj which composed of several IHTMLElements?
J := J + 1;
end;
end;
Result := vElementsRet;
end;
答案 0 :(得分:5)
您只需创建自己的容器类,例如TList<IHTMLElement>
或array of IHTMLElements
:
type
THTMLElements = array of IHTMLElement;
function GetElementsByClassName(ADoc: IDispatch; const strClassName: string): THTMLElements;
var
vDocument: IHTMLDocument2;
vElementsAll: IHTMLElementCollection;
vElement: IHTMLElement;
I, ElementCount: Integer;
begin
Result := nil;
ElementCount := 0;
if not Supports(ADoc, IHTMLDocument2, vDocument) then
raise Exception.Create('Invalid HTML document');
vElementsAll := vDocument.all;
SetLength(Result, vElementsAll.length); // set length to max elements
for I := 0 to vElementsAll.length - 1 do
if Supports(vElementsAll.item(I, EmptyParam), IHTMLElement, vElement) then
if SameText(vElement.className, strClassName) then
begin
Result[ElementCount] := vElement;
Inc(ElementCount);
end;
SetLength(Result, ElementCount); // adjust Result length
end;
的用法:强> 的
procedure TForm1.FormCreate(Sender: TObject);
begin
WebBrowser1.Navigate('http://stackoverflow.com/questions/14535755/how-to-get-an-ihtmlelementcollection-obj-which-composed-of-several-ihtmlelements');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Elements: THTMLElements;
I: Integer;
begin
// show Tags information for SO page:
Elements := GetElementsByClassName(WebBrowser1.Document, 'post-tag');
ShowMessage(IntToStr(Length(Elements)));
for I := 0 to Length(Elements) - 1 do
Memo1.Lines.Add(Elements[I].innerHTML + ':' + Elements[I].getAttribute('href', 0));
end;
将结果作为IHTMLElementCollection
返回的主要问题是IHTMLElementCollection
是由IHTMLDocument
在内部创建的IHTMLElementCollection
,我找不到任何创建方式vElementsRet := CoHTMLElementCollection.Create as IHTMLElementCollection
的新实例,并向其添加元素的引用,例如:
Class not registered
会导致{{1}}例外。