使用VB.NET,尝试将页面标题写入文本文件。我在这里难过:
Private Sub
Dim pagetitle As String
pagetitle = WebBrowser1.Document.Title
My.Computer.FileSystem.WriteAllText("page title.txt", pagetitle, False)
但是我收到一条错误,说“对象引用没有设置为对象的实例”。请帮忙!
答案 0 :(得分: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
答案 1 :(得分:0)
我的猜测是'WebBrowser1.Documen't为空。我不确定什么条件才能使Document不为null,但在尝试获取它的标题之前,你应该先检查它。
我偷了这个: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