问题
I'm trying to make the webbrowser click on a specific button within a webpage:
The html code for the button is something like <a class="btn btn-large play">
and the code I have so far to click this button is:
For Each Element As HtmlElement In WebBrowser2.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("btn btn-large play") Then
Element.InvokeMember("click")
End If
This works, but it makes the Webbrowser click the button again and again. Any idea how I can only make it do so twice?
回答1:
maybe simply like this? :)
For Each Element As HtmlElement In WebBrowser2.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("btn btn-large play") Then
Element.InvokeMember("click")
Element.InvokeMember("click")
return
End If
回答2:
And Why do you not try to detect the kind of element in the webbrowser:
Code snippet originally of @ElektroStudios, I'm just a lammer who pastes code without attribution.
Dim Document As HtmlDocument
Private Sub WebBrowser_DocumentCompleted(ByVal sender As System.Object, ByVal e As WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
Document = sender.Document
AddHandler document.Click, New HtmlElementEventHandler(AddressOf Document_Click)
End Sub
Private Sub Document_Click(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
Select Case Document.ActiveElement.TagName.ToLower
Case "button" : MsgBox("You've clicked a button")
Case "input" : MsgBox("You've clicked a input")
Case "a" : MsgBox("You've clicked a link")
Case Else
End Select
End Sub
Later you can replace MsgBox("You've clicked a link")
by some function or event or sub and do what do you want.. :D
回答3:
Try this:
Public count as integer=0
Private Sub WebBrowser_DocumentCompleted(ByVal sender As System.Object,ByVal e As WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
If count<2 then
For Each Element As HtmlElement In WebBrowser2.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("btn btn-large play") Then
Element.InvokeMember("click")
End If
count=count+1
end if
End Sub
回答4:
Would be sufficient to exit the FOR
loop when you've already clicked once the item, so try this:
For Each Element As HtmlElement In WebBrowser2.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("btn btn-large play") Then
Element.InvokeMember("click")
Exit For
End If
Next Element
来源:https://stackoverflow.com/questions/19463854/make-webbrowser-click-a-button-on-a-webpage-with-a-specific-class-once-in-vb-net