获取WebBrowser中的任一个Class或ID节点

     阅读 329 次    更新时间:2022/7/5    

获取WebBrowser中的任一个Class或ID节点

我们知道,在Webbrowser代码中,如果有<div id="toolbar" style="position: fixed; top: 0px; left: 0px; width: 100%; z-index: 1993;"> </div>时

我们可以使用WebBrowser1.OleObject.Document.getElementByID(‘toolbar’)访问到这个IHTMLElement网页元素

随后就可以有WebBrowser1.OleObject.Document.getElementByID(‘toolbar’).innerHtml

WebBrowser1.OleObject.Document.getElementByID(‘toolbar’).innerText

等多种手段访问元素的各种属性。

但是,如代码是<div Class="toolbar" style="position: fixed; top: 0px; left: 0px; width: 100%; z-index: 1993;"> </div>没有了ID属性,无法用getElementByID访问元素的属性怎么办?有人说getElementByClassName可以访问到这个元素,但IE9以下的浏览器不支持,所以就会给我们的程序增加兼容性问题。

为了更好的解决这个问题,我们就来写个函数解决这个问题。

(以下代码均从使用中的系统里摘取主体代码没改只是略有修改,如有语法错误请见谅)

程序代码如下:

Uses MSHTML

function GetElement(Doc: IHTMLDocument2; ClassName, IDName: string): IHTMLElement;
 
var
 
  elem: IHTMLElement;
 
  coll: IHTMLElementCollection;
 
  i: integer;
 
  sTmp, title: string;
 
begin
 
  Result:=nil; //初始化返回结果
 
  coll := Doc.all; //得到所有元素
 
  for i := 0 to coll.Length - 1 do //循环访问每个元素
 
  begin 
 
    elem := (coll.item(i, 0) as IHTMLElement);
 
    if ClassName<>'' then //提供ClassName表示按ClassName查找
 
    begin
 
      sTmp := Trim(string(elem.getAttribute(WideString('ClassName'), 0)));
 
                //获取ClassName,没有则是空
 
      if ClassName=sTmp then //是否与提供的ClassName相同
 
      begin
 
        Result:=elem; //返回这个元素
 
        Exit;
 
      end;
 
      if IDName<>'' then //提供ID表示按ID查找
 
      begin
 
        //WebBrowser1.OleObject.Document.getElementByID(IDName);
 
             //可以用常规的getElementByID语句访问,本文暂不采用
 
        sTmp := Trim(string(elem.getAttribute(WideString('ID'), 0)));
 
            //获取ID属性,与getElementByID效果相同
 
        if IDName=sTmp then //是否与提供的IDName相同
 
        begin
 
          Result:=elem; //返回这个元素
 
          Exit;
 
        end;
 
      end;
 
    end;
 
  end;
 
end;

使用范例:

procedure TFormMain.sSpeedButton36Click(Sender: TObject);
 
var
 
    StrStream:TStringStream;
 
    SetNoteStr: string;
 
    IHTML:IHTMLElement;
 
begin
 
    IHTML:=GetElement((WebBrowser1.Document as IHTMLDocument2), ‘toolbar’, ‘toolbar’); //查找并返回名为toolbar的元素
 
    if IHTML<>nil then //判断是否找到元素
    begin
      SetNoteStr:=IHTML.outerHTML;
      StrStream:=TStringStream.Create(SetNoteStr);
      try
        StrStream.Position:=0;
        ( WebBrowser2.Document as IPersistStreamInit).Load(TStreamadapter.Create(StrStream));
 
        //将本元素的代码用StringStream写入另一个浏览器中,相当于只显示某个元素的网页内容
      finally
          StrStream.Free;
      end;
    end;
 
end;

注意事项

1、如果确定要查找的是ClassName则IDName可为空,同理,确定查找的是IDName时ClassName可为空,如果都不确定,则与上面的程序一样,ClassName和IDName都写。

2、网页查找不到元素时返回空,所以查找结束后要判断下是否为空

 
 

Copyright 2003-2008 All Rights Reserved 自由风工作室 版权没有 [湘ICP备06002185号]
.