Visual Basic .NET 網頁程式設計
| 一位讀者請求擴充套件此書,以包含更多內容。 您可以透過 新增新內容 (學習方法) 或在 閱覽室 中尋求幫助。 |
| 一位華夏公益教科書使用者認為此頁面應該拆分為具有更窄子主題的較小頁面。 您可以透過將此大頁面拆分為較小的頁面來提供幫助。請確保遵循 命名策略。將書籍分成更小的部分可以提供更多關注點,並允許每個部分都能做好一件事,這有利於所有人。 |
.Net Framework 類庫中提供了網頁瀏覽功能。在本文中,我們將探討使用 Visual Basic .Net 載入和操作網頁的技術。您將需要 Microsoft Visual Basic .Net 2005 來使用示例程式碼。
讓我們看看 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。文件物件是網頁瀏覽器物件的屬性。
End If
System.Console.WriteLine(tmp)
Next
End Sub