【发布时间】:2015-08-26 18:01:29
【问题描述】:
我想获取“分页 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>
我尝试了很多,但没有成功。 可能有错字请忽略。 我需要一个工作代码。
这是我尝试过的代码 sn-p,但没有成功。
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;
提前致谢。
【问题讨论】:
标签: delphi twebbrowser