我正在做一个项目,我有一个需要设置自定义用户代理的 WebBrowser 控件,然后转到 Google 并填写搜索框,单击搜索按钮,然后单击搜索结果中的链接。不幸的是,我不能使用 HTTPWebRequest,它必须通过 WebBrowser 控件来完成。
在我添加代码来更改用户代理之前,一切正常。这是我的代码:
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("urlmon.dll", CharSet:=CharSet.Ansi)> _
Private Shared Function UrlMkSetSessionOption(dwOption As Integer, pBuffer As String, dwBufferLength As Integer, dwReserved As Integer) As Integer
End Function
Const URLMON_OPTION_USERAGENT As Integer = &H10000001
Public Sub ChangeUserAgent(Agent As String)
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, Agent, Agent.Length, 0)
End Sub
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
ChangeUserAgent("Fake User-Agent")
wb.Navigate("http://www.google.com", "_self", Nothing, "User-Agent: Fake User-Agent")
End Sub
Private Sub wb_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles wb.DocumentCompleted
Dim Source As String = wb.Document.Body.OuterHtml
Dim Uri As String = wb.Document.Url.AbsoluteUri
If Uri = "http://www.google.com/" Then
wb.Document.GetElementById("lst-ib").SetAttribute("value", "browser info")
wb.Document.All("btnK").InvokeMember("click")
End If
If Uri.Contains("http://www.google.com/search?") Then
Dim TheDocument = wb.Document.All
For Each curElement As HtmlElement In TheDocument
Dim ctrlIdentity = curElement.GetAttribute("innerText").ToString
If ctrlIdentity = "BROWSER-INFO" Then
curElement.InvokeMember("click")
End If
Next
End If
End Sub
End Class
问题在于以下代码:
wb.Document.GetElementById("lst-ib").SetAttribute("value", "browser info")
wb.Document.All("btnK").InvokeMember("click")
我认为问题可能是页面没有完全加载(框架问题),但我将有问题的代码放在计时器中进行测试,并得到了同样的错误。任何帮助将非常感激。