Delphi自動提交網頁表單和獲取框架網頁原始碼

一劍平江湖發表於2013-12-10

這兩個問題的實現原理其實是差不多的,所以放在一起介紹,單元MSHtml封裝了我們需要的功能。

首先,新建一個DELPHI工程,在USES部分新增MSHtml單元的引用。

然後,在窗體上放置一個TWebBrowser控制元件和四個按鈕。

最後,編寫四個按鈕的響應程式碼:

1. 自動提交網頁表單

procedure TForm1.Button1Click(Sender: TObject);
begin
  WebBrowser1.Navigate('http://www.baidu.com');
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  doc: IHTMLDocument2;
  oleObj: OleVariant;
begin
  doc := WebBrowser1.Document as IHTMLDocument2;
  if doc = nil then Exit;
  oleObj := doc.all.item('wd', 0) as IHTMLElement2;
  //網頁有一個名為“wd”的文字框:<input type="text" name="wd" id="kw" maxlength="100">
  oleObj.Value := 'Delphi'; //為文字框賦值
  oleObj := doc.all.item('su', 0) as IHTMLElement2;
  //網頁有一個ID為“su”的按鈕:<input type="submit" value="百度一下" id="su">
  oleObj.Click;  //點選按鈕,提交表單
end; 

2. 獲取框架網頁原始碼

 procedure TForm1.Button3Click(Sender: TObject);
begin
  WebBrowser1.Navigate('http://含有框架的網頁URL');
end;

procedure TForm1.Button4Click(Sender: TObject);
var
  doc, framedoc: IHTMLDocument2;
  frame_dispatch: IDispatch;
  ole_index: OleVariant;
  i: Integer;
begin
  doc := WebBrowser1.Document as IHTMLDocument2;
  if doc = nil then Exit;
  for i := 0 to doc.frames.length - 1 do
  begin
    ole_index := i;
    frame_dispatch := doc.frames.item(ole_index);
    if frame_dispatch = nil then Continue;
    framedoc := (frame_dispatch as IHTMLWindow2).document;
    if framedoc = nil then Continue;
    ShowMessage(framedoc.body.innerHTML);
  end;
end;
 

3. 獲取網頁所有連結

procedure TForm1.Button1Click(Sender: TObject);
var
  elem: IHTMLElement;
  coll: IHTMLElementCollection;
  i: integer;
  url, title: string;
begin
  coll := (WebBrowser1.Document as IHTMLDocument2).all;
  coll := (coll.tags('a') as IHTMLElementCollection);
  for i := 0 to coll.Length - 1 do
     begin //   迴圈取出每個連結
      elem := (coll.item(i, 0) as IHTMLElement);
      url := Trim(string(elem.getAttribute(WideString('href'), 0)));
      title := elem.innerText;
      ShowMessage(Format('連結標題:%s,連結網址:%s', [title, url]));
     end;
end;

相關文章