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 <body> 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;

例如:
<?xml version="1.0"?>
<!DOCTYPE html
        PUBLIC "//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Tip#36 Test</title>
  </head>
  <body>
     <p>Paragraph with no id</p>
     <p id="myid">Paragraph with id = myid</p>
  </body>
</html>


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;

相关阅读 >>

Delphi 获取本机公网ip

Delphi 动态调用chm文件

Delphi 首字母转换大写

Delphi 打开android应用信息

Delphi程序运行在64位机器连接odbc的问题

Delphi对access数据库安全加密方法

Delphi里实现对图片base64编码解码

Delphi 多核机器上编程实现将指定进程pid放到指定cpu上运行

Delphi远程开机再配合远程控制

Delphi 得到不同平台的录音文件保存路径

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...