我花了很长时间试图找到这个问题的答案。我从来没有意识到你可以使用 javascript 来调用点击。一旦我读到解决方案变得非常简单:
Public Function clickbyid(ByVal id)
If TheBrowser.Document.GetElementById(id) IsNot Nothing Then
Dim Headers As String = "" 'insert headers if you want to
TheBrowser.Navigate("javascript:document.getElementById('" & id & "').click();", "_self", Nothing, Headers)
'This keeps the function active until the browser has finished loading
Do While TheBrowser.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Return 1
Else
MessageBox.Show("Could not find link by id" & id)
Return Nothing
End If
End Function
您可能必须将“TheBrowser”更改为“WebBrowser1”。如果您不想返回结果,只需将其更改为 public sub 并删除 return 语句。
如果 htmlelement 没有 id则使用以下函数添加一个
Public Function clickbyelement(ByVal theButton As HtmlElement)
Try
'Generate a unique id to identify the element
Dim randomID = "vbAdded" & GetRandom(10000, 100000).ToString
'check to make sure the ID does not already exist
While TheBrowser.Document.GetElementById(randomID) IsNot Nothing
randomID = "vbAdded" & GetRandom(10000, 100000).ToString
End While
'add the ID to the element
theButton.SetAttribute("id", randomID)
'click
clickbyid(randomID)
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
' by making Generator static, we preserve the same instance '
' (i.e., do not create new instances with the same seed over and over) '
' between calls '
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
感谢 Dan Tao 提供的随机数:https ://stackoverflow.com/a/2677819/381273
测试和工作!