1

使用 VB.NET,尝试将页面标题写入文本文件。我被难住了:

Private Sub
    Dim pagetitle As String
    pagetitle = WebBrowser1.Document.Title
    My.Computer.FileSystem.WriteAllText("page title.txt", pagetitle, False)

但我收到一条错误消息,提示“对象引用未设置为对象的实例”。请帮忙!

4

2 回答 2

1

Document当它仍然等于 时,您很可能正在尝试访问该属性Nothing。将您的代码移动到控件的DocumentCompleted事件中WebBrowser,如下所示:

Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        If WebBrowser1.Document IsNot Nothing Then
            Dim pagetitle As String
            pagetitle = WebBrowser1.Document.Title
            My.Computer.FileSystem.WriteAllText("page title.txt", pagetitle, False)
        End If
End Sub
于 2013-03-29T16:52:57.333 回答
0

我的猜测是 'WebBrowser1.Documen' 不是空的。我不确定必须存在什么条件才能使 Document 不为空,但在尝试获取其标题之前,您绝对应该先检查一下。

我从以下位置偷了这个:http: //msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx

Private Sub webBrowser1_Navigating( _
    ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs) _
    Handles webBrowser1.Navigating

    Dim document As System.Windows.Forms.HtmlDocument = _
    webBrowser1.Document
    If document IsNot Nothing And _
        document.All("userName") IsNot Nothing And _
        String.IsNullOrEmpty( _
        document.All("userName").GetAttribute("value")) Then

        e.Cancel = True
        MsgBox("You must enter your name before you can navigate to " & _
            e.Url.ToString())
    End If 

End Sub
于 2013-03-29T16:53:29.027 回答