使WebBrowser在VB.net中单击具有特定类ONCE的网页上的按钮

时间:2013-10-19 08:01:00

标签: html vb.net click webbrowser-control getelementsbytagname

我正在尝试让网页浏览器点击网页中的特定按钮:

按钮的html代码类似<a class="btn btn-large play">,我到目前为止点击此按钮的代码是:

For Each Element As HtmlElement In WebBrowser2.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("btn btn-large play") Then
Element.InvokeMember("click")
End If

这样可行,但它会让Web浏览器一次又一次地单击该按钮。知道我怎么只能这样做两次吗?

4 个答案:

答案 0 :(得分:2)

也许只是这样? :)

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

答案 1 :(得分:1)

为什么你不试图检测webbrowser中的元素类型:

最初是@ElektroStudios的代码段,我只是一个没有归属地粘贴代码的lammer。

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

稍后您可以用某个函数或事件或子代替MsgBox("You've clicked a link")并执行您想要的操作..:D

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:0)

当你已经点击了一次项目后退出FOR循环就足够了,所以试试这个:

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