delphi 通过TWebBrowser文档中的ID查找HTML元素  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi 通过TWebBrowser文档中的ID查找HTML元素


uses
  MSHTML, SysUtils, Variants;

function GetElementById(const Doc: IDispatch; const Id: string): IDispatch;
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 := nil;
  // Check for valid document: require IHTMLDocument2 interface to it
  if not Supports(Doc, IHTMLDocument2, Document) then
    raise Exception.Create('Invalid HTML document');
  // Check for valid body element: require IHTMLElement2 interface to it
  if not Supports(Document.body, IHTMLElement2, Body) then
    raise Exception.Create('Can''t find element');
  // Get all tags in body element ('*' => any tag name)
  Tags := Body.getElementsByTagName('*');
  // Scan through all tags in body
  for I := 0 to Pred(Tags.length) do
  begin
    // Get reference to a tag
    Tag := Tags.item(I, EmptyParam) as IHTMLElement;
    // Check tag's id and return it if id matches
    if AnsiSameText(Tag.id, Id) then
    begin
      Result := Tag;
      Break;
    end;
  end;
end;

例如:
        PUBLIC "//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
    Tip#36 Test
 
 
     

Paragraph with no id

     

Paragraph with id = myid

 


procedure TForm1.FormShow(Sender: TObject);
begin
  WebBrowser1.Navigate(
    'file:///' + ExtractFilePath(ParamStr(0)) + 'test.html'
  );
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Elem: IHTMLElement;
begin
  Elem := GetElementById(WebBrowser1.Document, 'myid') as IHTMLElement;
  if Assigned(Elem) then
    ShowMessage(
      'Tag name = <' + Elem.tagName + '>'#10 +
      'Tag id = ' + Elem.id + #10 +
      'Tag innerHTML = "' + Elem.innerHTML + '"'
    );
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Elem: IHTMLElement;
begin
  Elem := GetElementById(WebBrowser1.Document, 'myid') as IHTMLElement;
  if Assigned(Elem) then
    Elem.innerHTML := 'My new text';
end;

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.059963941574097 seconds