无法使用mshtml.HTMLInputElement找到并单击提交按钮

时间:2012-01-31 22:40:50

标签: vb.net visual-studio browser

下面是一个HTML表单,下面是一个vb过程,“LoginExamp”输入用户名和密码。我无法找到按钮并单击它,因为它似乎没有显示为mshtml.HTMLInputElement。 “htmlInput.click()”永远不会运行。如何调整loginExamp代码以便单击该按钮。谢谢你的帮助。

<form id="loginform" name="loginform" method="post" action="">
<input id="username" class="formfield" type="text" value="User Name" maxlength="40" name="Xusername">
<input id="password" class="formfield" type="password" onfocus="clearDefault(this)" maxlength="40" name="Xpassword">
<button class="subButton" onclick="javascript: submitform()">submit!</button>
</form>

使用以下代码

Public Sub loginExamp()
    Dim objIE As SHDocVw.InternetExplorer
    Dim htmlDoc As mshtml.HTMLDocument
    Dim htmlInput As mshtml.HTMLInputElement
    Dim htmlColl As mshtml.IHTMLElementCollection
    Dim url As Object
    url = "http://localhost/ButtonClickTest.html" 'just a test page with the loginform above
    objIE = New SHDocVw.InternetExplorer
    With objIE
        .Navigate(url)
        .Visible = True
        While .Busy = True
            Threading.Thread.Sleep(2000)
        End While
        htmlDoc = .Document
        htmlColl = htmlDoc.getElementsByTagName("INPUT")
        While .Busy = True
            Threading.Thread.Sleep(2000)
        End While
        For Each htmlInput In htmlColl
            If htmlInput.name = "Xusername" Then
                htmlInput.value = "theusername" 'this works
            ElseIf htmlInput.name = "Xpassword" Then
                htmlInput.value = "thepassword" 'This works too
            End If
            If htmlInput.className = "subButton" Then 'This is never true
                htmlInput.click() 'This line never runs
            End If
        Next htmlInput
    End With
End Sub

1 个答案:

答案 0 :(得分:3)

我终于找到了自己问题的答案。以下是有效的代码。输入用户名和密码,并单击按钮。

Public Sub loginExamp()
    Dim objIE As SHDocVw.InternetExplorer
    Dim htmlDoc As mshtml.HTMLDocument
    Dim htmlInput As Object
    Dim url As String
    url = "http://localhost/N1/ButtonClickTest.html"'test page with the loginform above
    objIE = New SHDocVw.InternetExplorer
    With objIE
        .Navigate(url)
        .Visible = True
        While .Busy = True
            Threading.Thread.Sleep(2000)
        End While
        htmlDoc = .Document
        Dim htmlColl As mshtml.HTMLFormElement = DirectCast(htmlDoc.forms.item("loginform"), mshtml.HTMLFormElement)
        While .Busy = True
            Threading.Thread.Sleep(2000)
        End While
        For Each htmlInput In htmlColl
            If htmlInput.name = "Xusername" Then
                htmlInput.value = "theusername"
            ElseIf htmlInput.name = "Xpassword" Then
                htmlInput.value = "thepassword"
            End If
            If htmlInput.className = "subButton" Then
                htmlInput.click()
            End If
        Next htmlInput
    End With
End Sub