Delphi:TWebBrowser - 获取类

时间:2015-08-26 18:01:30

标签: delphi twebbrowser

我希望得到类#34; pagination pagination_wrapper"的所有标签的href。 我正在使用Delphi XE2和TWebBrowser

<ul class="pagination pagination_wrapper"> 
    <li>
        <a href="http://domain.com/1">1</a>
    </li> 
    <li>
        <a href="http://domain.com/2">2</a>
    </li> 
    <li>
        <a href="http://domain.com/3">3</a>
    </li>
    <li>
        <a href="http://domain.com/4">4</a>
    </li> 
    <li>
        <a href="javascript:void(0);">#</a>
    </li> 
</ul>

我尝试了很多但没有成功。 可能有TYPO请忽略。 我需要一个有效的代码。

这是我尝试过的没有运气的代码段。

var
    MyDiv, HtmlElem1 : IHTMLElement;
    HtmlAnchor       : IHTMLAnchorElement;
    AnCol1, AnCol2   : IHTMLElementCollection;
begin

  GetElementByClass(ewb.Document, 'pagination pagination_wrapper', MyDiv); // works fine
  Supports(MyDiv.children, IHTMLElementCollection, AnCol1);

  ShowIt(AnCol1.Length-1);      // 5

  for i := 0 to AnCol1.Length-1 do
  begin
    if Supports(AnCol1.item(i,0), IHTMLElement, HtmlElem1) then
    begin
      ShowIt('HtmlElem1: '+HtmlElem1.innerHTML);    // shows perfect <a> HTML markup

      Supports(HtmlElem1.children, IHTMLElementCollection, AnCol2);
      ShowIt(AnCol2.length);    // 1

      Supports(AnCol2.tags('a'), IHTMLElementCollection, AnCol2);

      ShowIt(AnCol2.length);    // 1

      if Supports(AnCol2.item(i, 0), IHTMLAnchorElement, HtmlAnchor) then
        ShowIt(HtmlAnchor.href);
      else
        ShowIt('Not Anchor element');   // always prints this, even IHTMLElement does not work
    end
  end;
end;

=============================================== ==========================

function GetElementByClass(const Doc: IDispatch; const ClassName: string; var element : IHTMLElement): Boolean;
var
  Document: IHTMLDocument2;     // IHTMLDocument2 interface of Doc
  Body: IHTMLElement2;          // document body element
  Tags: IHTMLElementCollection; // all tags in document body
  Tag: IHTMLElement;            // a tag in document body
  i: Integer;                   // loops thru tags in document body
begin
  Result := False ;
  element := nil;

  if not Supports(Doc, IHTMLDocument2, Document) then
    raise Exception.Create('Invalid HTML document');

  if not Supports(Document.body, IHTMLElement2, Body) then
    raise Exception.Create('Can''t find <body> element GetElementByClass()');

  Tags := Body.getElementsByTagName('*');

  for i := 0 to Pred(Tags.length) do
  begin
    Tag := Tags.item(I, EmptyParam) as IHTMLElement;
    if Pos(ClassName, string(Tag.className)) > 0 then
    begin
      element := Tag;
      Result := True;
      Break;
    end;
  end;
end;

提前致谢。

1 个答案:

答案 0 :(得分:1)

更改以下内容:

if Supports(AnCol2.item(i, 0), IHTMLAnchorElement, HtmlAnchor) then

if Supports(AnCol2.item(0, EmptyParam), IHTMLAnchorElement, HtmlAnchor) then