如何获得由几个IHTMLElements组成的IHTMLElementCollection obj?

Mar*_*Lin 5 delphi pascal mshtml ihtmldocument2

伙计们:我在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;
Run Code Online (Sandbox Code Playgroud)

kob*_*bik 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;
Run Code Online (Sandbox Code Playgroud)

用法:

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;
Run Code Online (Sandbox Code Playgroud)

返回结果的主要问题IHTMLElementCollection是,它IHTMLElementCollection是由内部创建的IHTMLDocument,我找不到任何方法来创建新的实例IHTMLElementCollection并向其添加元素的引用,例如:

vElementsRet := CoHTMLElementCollection.Create as IHTMLElementCollection
Run Code Online (Sandbox Code Playgroud)

将导致Class not registered例外.