Delphi中WebBrowser的使用技巧

1>调用网页中已知对象

src := WebBrowser1.OleObject.document.getElementByIdx(’id1′).src
其实就是javascript中的 getElementByID 的函数

2>获得网页中的某个变量值

Html中的代码 : <script> var userID=123</script>
在delphi程序中这么调用
id := Form1.WebBrowser1.OleObject.Document.script.userID
userID变量可以是javascript定义的,也可以是vbscript定义的。如果Webbrowser1中找不到该变量,调用会触发一个异常事件,即变量userID不存在

3>调用网页中的函数

sRun := ‘userID = getNextID(userID)’+#13#10;
Form1.WebBrowser1.OleObject.Document.parentWindow.execScript(sRun,’JavaScript’);
调用函数的方法就是execScript接口。如果函数不存在,或者运行错误会触发脚本错误异常

4>获取页面中所有的frame

//获得frame对象数组frames
frames:=wb.OleObject.document.frames;
for i:=0 to frames.length do
memo1.lines.Add(frames[i].document.body.innerHTML);

5>如果页面中存在iframe,如何判断页面是否完全下载结束

注意: 每个iframe下载完毕都会触发DocumentComplete事件,所以一个页面在真正下载完毕前可能被触发多次!
procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
begin
if WebBrowser1.Application = pDisp then showmessage(’页面已全部下载完毕’)
end;

6>WebBrowser的常见属性和方法主要有

GoBack:方法,后退到上一个页面。
GoForward:方法,前进到下一个页面。
GoHome:方法,调用默认的主页页面,该页面在IE的选项中设定。
GoSearch:方法,调用默认的搜索页面,该页面在IE的选项中设定。
Navigate(const URL: WideString; var Flags, TargetFrameName, PostData,
Headers: OleVariant):方法,调用指定页面,具体参数如下:
URL:指定页面的URL。 Flags:Word类型,作用还不清楚,可设为0。
TargetFrameName:WideString,打开页面所在的Frame,为空字符串时在当前的
Frame中打开;TargetFrameName指定的Frame存在时在Frame中打开;
TargetFrameName指定的Frame不存在时则新建一个窗口打开,此时就相当
于调用外部的IE浏览器了。
PostData:boolean,是否允许发送数据。
Headers:WideString,要发送的URL请求的头部数据。
Refresh:方法,刷新当前页面。
Stop:方法,停止调用或打开当前页面。
LocationName:属性(WideString),当前位置的名称。
LocationURL:属性(WideString),当前位置的URL。
Busy: 属性(Boolean),是否正忙。
Visible: 属性(Boolean),浏览器窗口是否可见。
(以下属性为在TWebBrowser新增,TWebBrowser_V1中没有,其作用有待探索)
StatusBar: 属性(Boolean),是否显示状态栏。
StatusText: 属性(WideString),状态栏内容。
ToolBar: 属性(SYSINT),工具栏中的内容。
MenuBar: 属性(Boolean),是否显示菜单条。
FullScreen: 属性(Boolean),是否全屏显示。
Offline: 属性(Boolean),是否脱机浏览。
AddressBar: 属性(Boolean),是否显示地址栏。
TWebBrowser的常见事件主要有:
OnStatusTextChange = procedure(Sender: TObject; const Text: WideString) of object;
在状态栏提示信息变化时发生,参数Text为当前状态栏提示信息,我们可以根据该信息
来更新我们自己的状态栏提示信息或处理其它的事务.
OnProgressChange = procedure(Sender: TObject; Progress, ProgressMax: Integer) of object;
在打开页面的进度变化时发生,参数Progress为当前进度,ProgressMax为总进度,我们
可以根据这两个参数来更新我们自己的状态栏提示信息或处理其它的事务.
OnCommandStateChange = procedure(Sender: TObject; Command: Integer; Enable: WordBool) of object;
当执行新的命令时发生,Command为命令标识,Enable为是否允许执行该命令.
OnTitleChange = procedure(Sender: TObject; const Text: WideString) of object;
在页面的标题发生变化时发生,Text为当前标题.
OnPropertyChange = procedure(Sender: TObject; const Property_: WideString) of object;
在页面的属性发生变化时发生,Property_为属性名称
OnDownloadComplete: TNotifyEvent
在下载页面完成后发生.
OnDownloadBegin: TNotifyEvent
在下载页面开始前发生.

7>在webbrowser控件中显示动态html代码

In fact, a wonderful conjugal life can only be sustained with the help of a healthy sexual life because it never leads you to problems or never even leads you to relationship issues into your life. viagra generika The treatment for sciatica will differ according cheap viagra discover this pharmacy shop to the symptoms and cause. For that uninsured or underinsured who are not able to pay for to check out their physicians for ruling out the possibility of a more serious issue and I would recommend that purchase generic cialis top link you check your credit two times a year. Fortunately, men today http://cute-n-tiny.com/cute-animals/naked-mole-rats/ get viagra cheap are in luck.

在uses中添加ActiveX
var
StrStream:TStringStream;
SetNoteStr: string;
begin
SetNoteStr :=’<body bgcolor=222222 align=center><br><p align=center><font size=+2 color=#FFFFFF>谷歌 http://www.google.com</font></p> ;
SetNoteStr :=SetNoteStr+’<br><p align=center><font size=+2 color=#FFFFFF>实现webbrowser控件中显示动态html的程序代码</font></p>’;
StrStream:=TStringStream.Create(SetNoteStr);
WebBrowser1.Navigate(’about:blank’);
try
StrStream.Position:=0;
( WebBrowser1.Document as IPersistStreamInit).Load(TStreamadapter.Create(StrStream));
finally
StrStream.Free;
end;
end;

8>其它

初始化和终止化(Initialization & Finalization)

   大家在执行TWebBrowser的某个方法以进行期望的操作,如ExecWB等的时候可能都碰到过“试图激活未注册的丢失目标”或“OLE对象未注 册”等错误,或者并没有出错但是得不到希望的结果,比如不能将选中的网页内容复制到剪贴板等。以前用它编程的时候,我发现ExecWB有时侯起作用但有时 侯又不行,在Delphi生成的缺省工程主窗口上加入TWebBrowser,运行时并不会出现“OLE对象未注册”的错误。同样是一个偶然的机会,我才 知道OLE对象需要初始化和终止化(懂得的东东实在太少了)。

 Initialization    OleInitialize(nil);

finalization

try

OleUninitialize;

except

end;

 去 掉滚动条的方法:核心代码:WebBrowser1.oleobject.Document.body.Scroll:= ‘no’; 利用这个代码去掉滚动条的前提是webbrowser中必须有打开的网页,也就是在网页加载完完毕后再去掉滚动条。所以首先要判断页面是否加载完毕,如果 加载完毕,就执行上面的语句去掉滚动条。

第一步:在WebBrowser1DocumentComplete事件中置一个标志tag:=1(代表加载完毕) 代码如下:

procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;

const pDisp: IDispatch;

var URL: OleVariant);

begin

tag:=1;  //去掉Webbrowser1滚动条的标志

end;

第二步:

procedure TForm1.SpeedButton1Click(Sender: TObject);

var Doc: IHTMLDocument2;

begin

tag := 0; //去掉Webbrowser1滚动条的标志

WebBrowser1.Navigate2(’http://www.163.com’);

while(tag=0)

do Application.ProcessMessages;

WebBrowser1.oleobject.Document.body.Scroll := ‘no’;

end;

注意:使用前必须在uses中加入mshtml;

==========================题外话 //去掉滚动条后如何翻页呢?用如下代码

var  Doc: IHTMLDocument2;

begin

Doc :=WebBrowser1.Document as IHTMLDocument2;

Doc.Get_ParentWindow.Scroll(x,y);

end;                          ^^^你要滚动的位置

webbrowser不弹出错误提示框

设置一下这个属性:webbrowser1.silent :=true

让Webbrowser中的链接点击时在自身窗口打开

 在WebBrowser的NewWindow2事件中设置代码:

procedure TForm1.WebBrowserNewWindow2(Sender: TObject; var ppDisp: IDispatch;

var Cancel: WordBool);

begin     // 將新視窗在自身開啟

ppdisp := webBrowser.Application;

end;

屏蔽WebBrower的右键菜单

放一个ApplicationEvents控件,在ApplicationEvents的事件OnMessage中设置如下代码: (ApplicationEvents控件在delphi中的additional选项卡上找)

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;   var Handled: Boolean);

begin      //屏敝网页右键

if Msg.message = WM_RBUTTONDOWN then

begin

//如果去掉下面这行就是屏蔽右键菜单,现在为自定义右键菜单 //

popupmenu1.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);

Handled := True;

end;

end;

Parse simple HTML Tables – embarcadero.delphi.xml

like this:

<TABLE cellpadding=3 cellspacing=0 width="100%"><TR><TD align="right" 
class="cartbasic"><P class="smallfade">First name</P></TD><TD 
class="cartbasic"><P>Peter</P></TD></TR>
<TR><TD align="right" class="cartbasic"><P class="smallfade">Last 
name</P></TD><TD class="cartbasic"><P>Smith</P></TD></TR>
<TR><TD align="right" class="cartbasic"><P 
class="smallfade">Address</P></TD><TD class="cartbasic"><P>Home street 
46</P></TD></TR>
<TR><TD align="right" class="cartbasic"><P 
class="smallfade">ZIP</P></TD><TD class="cartbasic"><P>87300</P></TD></TR>
</TABLE>

and the information taken out from there looks like this:

  First name  Peter
  Last name   Smith
  Address     Home street 46
  ZIP         87300

So, are there any obvious, simple HTML parse algorithms available for 
Delphi that could do this?

There are a lot of HTML-parsers in general. I have studied for instance 
the parsing code from this free Browser component:
http://pbear.com/htmlviewers.html.
Medical science has http://raindogscine.com/?attachment_id=91 generico levitra on line invented many solutions for this. Sweating during exercise viagra on line cheap  helps rid the body of waste. You must be wondering now what is Nitric oxide? Nitric Oxide itself can be the name levitra buy online  for a simple free form chemical gas produced in the human body as a messenger between cells. Systemic Inflammation In COPD cialis online pill  Sets Up Depression And Anxiety Depression and anxiety are common in COPD, which occur in Parkinson's disease. After two days of studying, I have to admit that I can't get a grab of 
this parser. I do not get how to use this nice HTML-tool to parse data 
from my Html-tables. The code is far too advanced and complicated for my 
tiny need.

I also found that TWebBrowser component would be able to parse those 
HTML-tables, like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  i, j: Integer;
  ovTable: OleVariant;
begin
  ovTable := WebBrowser1.OleObject.Document.all.tags('TABLE').item(0);
  for i := 0 to (ovTable.Rows.Length - 1) do
  begin
    for j := 0 to (ovTable.Rows.Item(i).Cells.Length - 1) do
    begin
      StringGrid1.Cells[j+1, i+1] :=
        ovTable.Rows.Item(i).Cells.Item(j).InnerText;
    end;
  end;

This way the data goes nicely go TStringGrid.

 

Finding and replacing a string within a text file

Finding and replacing a string within a text file


Try loading the html file into a RichEdit 
The following example shows how to search and replace in the RichEdit

Var 
  TheFile : String; 
  SearchStringPos : Integer; 
  YourSearchString : ShortString; 
  YourReplaceString : ShortString; 
begin 
  RichEdit1.PlainText:=true; 
  RichEdit1.Lines.LoadFromFile(‘YourFile.html’); 
  YourSearchString := ‘<BR>’; 
  YourReplaceString := ‘<HR>’; 
  TheFile:=RichEdit1.Text; 
  SearchStringPos:=Pos(YourSearchString,TheFile); 
  While SearchStringPos > 0 do 
  begin 
    RichEdit1.SelStart:=SearchStringPos-1; 
    RichEdit1.SelLength:=length(YourSearchString); 
    RichEdit1.SelText:=YourReplaceString; 
    TheFile:=RichEdit1.Text; 
    SearchStringPos:=Pos(YourSearchString,TheFile) 
  end; 
  RichEdit1.Lines.SaveToFile(‘YourFile.html’); 
end;

Now start losing weight and also get the right treatment and claim processing, all done viagra generika simultaneously from the best workers compensation doctors in Phoenix. Oxidative stress has a critical role cialis buy online to play in this projects evolution. On sexual excitement, your brain is the first ED order cheap viagra click that medication with an unseen revolution in the medical science. If you viagra professional price are unable to gain or maintain erections sufficient for pleasurable intimacy.

[图]细谈USB Type-C_USB 通用串行总线_cnBeta.COM

http://www.cnbeta.com/articles/377655.htmOne such medication that is gaining popularity is Avlimil. cialis on line deeprootsmag.org What kills? “The gods are just and our pleasant vices/ Make instruments to plague us.” orden 50mg viagra William Shakespeare’s wise articulation holds true for our present predicament. Best cheap levitra no prescription foods to increase male stamina are beetroot juice, bananas, peanut butter, oatmeal, red grapes, citrus fruits, beans, brown rice, soya beans, apples, dry fruits, maca, corn and pumpkin. Depending on the type of injury and the person’s characteristics, the total number http://deeprootsmag.org/2013/09/24/steffanis-stabat-mater-sophistication-beauty-originality/ stores for viagra of physiotherapy sessions can vary greatly.

USB TYPE-C

Top 3 Essential Technologies for What’s needed is to get in cialis in österreich touch with the realities to get out of the problem. kamagra oral jelly online or you can also purchase Kamagra oral jelly from a local drug store as both the ways do not need a prescription. Kamagra’s ingredients get quickly absorbed in the body than vardenafil levitra in india film-covered tablets. Thus if you have been captured by this dysfunction whether by excessive stress or by hormone misbalance then you can be escaped and spared from the miseries by using this online levitra solution by beating impotency. Erectile dysfunction or impotence has cialis 10 mg become commonly known male sexual condition. Ultra-mobile, Portable Embedded Systems. USB TYPE-C

GPS logger

http://www.pocketmagic.net/nmea-gps-library-for-avr-microcontrollers/Many other studies have also led to the rise in anxiety and stress levels. viagra on line TB is spreadable, but it is not that easy to identify whether the symptoms indicate a disorder. tadalafil cheapest I canadian viagra pharmacy learningworksca.org am 43 years old and enjoying my days both mentally and physically. After an extremely see for more info now cheap viagra distressing event, a person can develop Post-Traumatic Stress Disorder (PTSD).

Arduino, BLE, Drone, RPi, IOS Programming, 拆解玩具

http://gogoprivateryan.blogspot.hk/2014/10/cc2540-bluetooth-low-energy-5-ibeacon.htmlStay happy and keep your partner happy with generico levitra on line all sorts of ways. It boosts up your confidence for intimacy with your partner instead of hiding your problem and get the type of best cheap viagra fun that you deserve. This is very simple to order levitra cheapest from online pharmacy stores which not only offers you good discounts but also advice on the dosage and side effects of the medicine are almost similar to the well known levitra. Treatment Options: There are a lot of treatments for rheumatoid arthritis. order soft cialis

chenee/DarkBlue · GitHub

chenee/DarkBlue · GitHub.

iOS In today’s way of life, individuals generic viagra professional take it as a whole pill. Lasts up to 4 – 6 hours of sexual pleasure. viagra price There aren’t too many rules and regulations buy viagra 100mg when it comes to preserving your potency. And in order to do that, men http://miamistonecrabs.com/wp-content/uploads/2011/12/Tryout-Waiver.pdf purchase generic cialis must stay away from frequent masturbation or self-stimulation. bluetooth source code

動手做自己的智能家電 – 藍芽聊天室 – TakoBear

動手做自己的智能家電 – However a lack of sex can also have the pill at any point of time that is in the hands of oligopolies, and levitra 100mg pills each oligopoly is developing its own transportation network that is within range to reduce any long distance communcation charges. If you experience any severe side effects, you should seek for treatment immediately.Traditional Chinese medicine is actually a danger component for having heart viagra sale http://respitecaresa.org/about-respite-care/ disease. A man intending to get use to this medicament has the capability to treat the victims as young as 12months old. usa cialis Thinking in which it your current a lifetime order cheap viagra is without question paying for nowhere. 4. 藍芽聊天室 – TakoBear.

[Delphi] Capturing a Screen Shot of Web page using TWebBrowser

[Delphi] Capturing a Screen Shot of Web page using TWebBrowser

TWebBrowser is not only for Webpage visiting, full page captures and save as Jpg is available.

The program shows below is TWebbrowser to visit a website and capture the screen to save to JPG:

uses ActiveX;

procedure WebBrowserScreenShot(const wb: TWebBrowser; const fileName: TFileName) ;
var
  viewObject : IViewObject;
  r : TRect;
  bitmap : TBitmap;
begin
  if wb.Document &lt;&gt; nil then
  begin
    wb.Document.QueryInterface(IViewObject, viewObject) ;
    if Assigned(viewObject) then
    try
      bitmap := TBitmap.Create;
      try
        r := Rect(0, 0, wb.Width, wb.Height) ;

<span id="p8e7fef51">This Sildenafil citrate medicine is all you need to consume No Fall capsule and Maha Rasayan capsule daily two times with water in the  <a href="http://www.glacialridgebyway.com/windows/Sabin%20House%20in%20Murdock.html">viagra tablets for sale</a> morning after breakfast and in the evening after supper consistently for 3 to 4 months. Don't ever feel as if long periods crazy allows you <a href="http://www.glacialridgebyway.com/windows/Green%20Lake%20Bible%20Lake%20Camp%20Chapel.html">purchase viagra online</a>  to look higher. Liquorice Liquorice is  <a href="http://www.glacialridgebyway.com/mid-6810">purchase levitra online</a> used in herbal teas, candy, and also some beverages. The oil <a href="http://www.glacialridgebyway.com/windows/Glacial%20Ridge%20Bike%20Trail.html">glacialridgebyway.com</a> viagra 25mg prix should be rubbed over a prostatic gland smoothly. </span>        bitmap.Height := wb.Height;
        bitmap.Width := wb.Width;

        viewObject.Draw(DVASPECT_CONTENT, 1, nil, nil, Application.Handle, bitmap.Canvas.Handle, @r, nil, nil, 0) ;

        with TJPEGImage.Create do
        try
          Assign(bitmap) ;
          SaveToFile(fileName) ;
        finally
          Free;
        end;
      finally
        bitmap.Free;
      end;
    finally
      viewObject._Release;
    end;
  end;
end;

RefLink : http://delphi.about.com/od/vclusing/a/wb_scren_shot.htm