2010年12月31日 星期五

.NET 網頁自動輸入及Submit form

記錄一下.net要怎麼連外部網頁並進行自動輸入與Submit form

先加入namespace
Imports System.Net

Dim wbBrowser As New WebBrowser()

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   '加入瀏覽器正在轉址時的event
   AddHandler wbBrowser.Navigating, AddressOf wbBrowser_Navigating
   '加入瀏覽器轉址完成的event
   AddHandler wbBrowser.Navigated, AddressOf wbBrowser_Navigated
End Sub

Private Sub wbBrowser_Navigating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs)
   '當網頁按鈕click flag為true,且發生轉址時
   If WebSubmit = True Then
      '設定瀏覽器轉址狀態flag
      WebNavigating = True
      '清除網頁按鈕click flag
      WebSubmit = False
   End If
End Sub

Private Sub wbBrowser_Navigated(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs)
   '當瀏覽轉址狀態flag為true,且已轉址完成時
   If WebNavigating = True Then
      '取得結果頁的內容
      GetResult()
      '清除瀏覽器轉址狀態
      WebNavigating = False
   End If
End Sub

'/***等待瀏覽器處理完成***/
Private Sub WaitForResponse()
   '如果Browser的狀態還未準備好,就繼續處理
   Do Until wbBrowser.ReadyState = WebBrowserReadyState.Complete
      Application.DoEvents()
   Loop
End Sub

'/***輸入網頁控制項的內容***/
Private Function InputControl(ByVal ControlName As String, ByVal ControlValue As String) As Boolean
   Try
      '取得網頁中的控制項並給其值
      '前提是控制項要有設Name屬性才能用此方式抓到
      '否則就要用wbBrowser.Document.getElementById method
      wbBrowser.Document.Body.All(ControlName).InnerText = ControlValue
      Return True
   Catch ex As Exception
      Return False
   End Try
End Function

'/***執行網頁按鈕的click動作***/
Private Function SubmitForm() As Boolean
   Try
      '因為目標網頁的Submit button沒有Name和ID屬性
      '所以只好用TagName來取得所有的Input物件
      '再判斷其type屬性是Submit的執行click動作
      Dim InputObjs As HtmlElementCollection = wbBrowser.Document.Body.GetElementsByTagName("input")

      For e As Integer = 0 To InputObjs.Count - 1
         Dim btnSubmit As HtmlElement = InputObjs(e)
         If btnSubmit.GetAttribute("type").ToString().ToUpper() = "SUBMIT" Then
            '設定網頁按鈕click flag
            WebSubmit = True
            btnSubmit.DomElement.click()
            e = InputObjs.Count
         End If
      Next
      Return True
   Catch ex As Exception
      Return False
   End Try
End Function

'/***取得網頁內容***/
Private Sub GetResult()
   Dim strWholeBody As String = wbBrowser.Document.Body.InnerHtml
   ...
End Sub

Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
   '連到目標網頁()
   wbBrowser.Navigate(tbUrl.Text)

   '等待網頁回應
   WaitForResponse()

   '將值填入目標控制項
   If InputControl("check", tbValue.Text) = True Then
      '送出 Form
      SubmitForm()
   End If
   '如果瀏覽器還在轉址狀態,就繼續讓瀏覽器處理
   While WebNavigating
      Application.DoEvents()
   End While
End Sub

沒有留言:

張貼留言