用于点击的类名的getelement

时间:2016-03-16 14:10:10

标签: vb.net visual-studio-2013

我在VB.NET中使用Web浏览器控件创建一个Windows窗体,但无法单击下面的代码。

<input type="Submit" class="btn btnSearch bold include_WidthButton" value="Search">

我可以通过ID获取元素,但不能通过classname获取。请帮我这么多谷歌搜索没有帮助我。

这就是我的尝试:

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("btn btnSearch bold include_WidthButton")
    If Element.OuterHtml.Contains("btn btnSearch bold include_WidthButton") Then
        Element.InvokeMember("click")
    End If
Exit For

2 个答案:

答案 0 :(得分:0)

没有本机函数可以使用webbrowser文档按类获取元素集合。但是,您可以使用函数创建自己的集合,并使用document.all属性循环遍历所有元素。

Function ElementsByClass(document As HtmlDocument, classname As String)
    Dim coll As New Collection
    For Each elem As HtmlElement In document.All
        If elem.GetAttribute("className").ToLower.Split(" ").Contains(classname.ToLower) Then
            coll.Add(elem)
        End If
    Next
    Return coll
End Function

使用就像这样:

Private Sub UpdatBtn_Click(sender As System.Object, e As System.EventArgs) Handles UpdatBtn.Click

    For Each elem As HtmlElement In ElementsByClass(WebBrowser1.Document, "form")
        elem.SetAttribute("className", elem.GetAttribute("className") & " form-control")
    Next

End Sub

我看到你试图将你的集合基于整个className而不是单个类,所以你需要稍微修改一下。

答案 1 :(得分:0)

这是我的解决方案:

Public Sub clickButton(ByVal web As WebBrowser, ByVal tagname As String, ByVal attr As String, ByVal contains As String, ByVal sleep As Integer)
    Try
        If (web.Document IsNot Nothing) Then
            With web.Document
                For Each Elem As HtmlElement In .GetElementsByTagName(tagname)
                    If (Elem.GetAttribute(attr).Contains(contains)) Then

                        Elem.InvokeMember("Click")
                        Thread.Sleep(sleep)
                        Return
                    End If
                Next
            End With
        End If
    Catch ex As Exception
        Show_Error(MODULE_NAME, "clickButton")
    End Try
End Sub

使用:

clickButton(WebBrowser1, "button", "classname", "btn btnSearch bold include_WidthButton", 2000)