跳到內容

Visual Basic .NET 網頁程式設計

0% developed
來自華夏公益教科書,開放的書籍,開放的世界

.Net Framework 類庫中提供了網頁瀏覽功能。在本文中,我們將探討使用 Visual Basic .Net 載入和操作網頁的技術。您將需要 Microsoft Visual Basic .Net 2005 來使用示例程式碼。

Web 瀏覽器物件

[編輯 | 編輯原始碼]

讓我們看看 Web 瀏覽器物件。此物件存在於 .NET Framework 類庫中。它是框架 2.0 版中的新功能。如果您分發使用此物件的程式,目標系統必須安裝 2.0 版(或更高版本)。

Public wbInCode As New WebBrowser

WebBrowser 物件不需要表單。您可以使用它以程式設計方式載入網頁而無需顯示它們。但是,您的程式會受到您為傳統瀏覽器設定的配置設定的約束。例如,如果您允許彈出視窗,那麼您載入到 wbInCode 物件中的任何網頁都將有權啟動彈出視窗。彈出視窗將在瀏覽器視窗中啟動,這些視窗位於您的程式外部,即使您的 WebBrowser 物件沒有在視窗中顯示也是如此。

如果 JavaScript 方法在載入的頁面上崩潰,並且您配置為在發生此類錯誤時停止,則網頁瀏覽器控制元件也將停止。您的程式將掛起。簡而言之,如果您計劃在自動化環境中使用該控制元件,則需要仔細檢視您的預設瀏覽器設定。否則,您會發現您的應用程式因有缺陷的網頁而被阻止,並且您的顯示器被彈出視窗淹沒。

將網頁載入到瀏覽器物件

[編輯 | 編輯原始碼]

使用 WebBrowser 物件的 Navigate 方法載入網頁

wbInCode.Navigate("http://www.usatoday.com")

等待載入操作完成

 While (wbInCode.IsBusy = true)
   ' Theoretically we shouldn’t need this, but experience says otherwise.
   ' If we just bang on the IsBusy() method we will use up a lot of CPU time
   '  and probably bog down the entire computer.
     Application.DoEvents()
 end

您還可以讓物件在載入完成後通知您。DocumentCompleted 事件在頁面載入後觸發。此示例添加了一個事件處理程式方法,該方法將在頁面載入完成後呼叫。

 Private Sub MyWebPagePrinter()
   Dim wbInCode As New WebBrowser   ' Create a WebBrowser instance. 
   ' Add an event handler. The AddHandler command ‘connects’ your method called
   ' ReadyToPrint() with the DocumentCompleted event. The DocumentCompleted event
   ' fires when your WebBrowser object finishes loading the web page.
   AddHandler wbInCode.DocumentCompleted, _ 
              New WebBrowserDocumentCompletedEventHandler (AddressOf ReadyToPrint)
   ' Set the Url property to load the document.
   wbInCode.Navigate("http://www.usatoday.com")
 End Sub
[編輯 | 編輯原始碼]

我們還沒有完成。以下是我們在前面程式碼中提到的 ReadyToPrint 方法。方法的名稱是任意的,但引數列表是必需的。請注意,您不必顯式呼叫此方法。它將在網頁載入後由 WebBrowser 物件為您呼叫。

   Private Sub ReadyToPrint(ByVal sender As Object, _
                             ByVal e As WebBrowserDocumentCompletedEventArgs)
       ' Create a temporary copy of the web browser object.
       '  At the same time we will assign it a value by coercing the sender argument
       '  that was passed into this method.
       Dim webBrowserTmp As WebBrowser = CType(sender, WebBrowser)
       ' We know that the web page is fully loaded because this method is running.
       ' Therefore we don’t have to check if the WebBrowser object is still busy.
       ' It’s time to print…
       webBrowserTmp.Print()
   End Sub

訪問儲存在瀏覽器物件中的 HTML

[編輯 | 編輯原始碼]

載入網站後,您可以訪問底層的 HTML。文件物件是網頁瀏覽器物件的屬性。

           End If
           System.Console.WriteLine(tmp)
       Next
   End Sub
華夏公益教科書