在网页上以登录表单输入用户名和密码

时间:2015-11-10 19:07:42

标签: javascript excel vba excel-vba

使用Excel VBA,我尝试登录网站。

这是我的代码:

Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
Sub Website_Login()

Dim oHTML_Element As IHTMLElement
Dim sURL As String

sURL = "https://www.domain.com/login.html"

Set oBrowser = New InternetExplorer
'oBrowser.Silent = True
'oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True

Do
Loop Until oBrowser.ReadyState = READYSTATE_COMPLETE

Set HTMLDoc = oBrowser.Document

With HTMLDoc
  HTMLDoc.getElementById("username").Value = "user"
  HTMLDoc.getElementById("password").Value = "password"
End With

For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
  oHTML_Element.Click
  Exit For
Next

oBrowser.Quit

End Sub

此代码中的Javascript指令正在运行。如果我进入页面并输入它们,它们就能正常工作。但是当我运行代码时,IE会打开,但它不会进入用户/通行证并单击按钮。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

我刚刚测试了这段代码,但它确实有效。

唯一的区别是我使用Late Binding(懒得设置所有引用)并且我将While .Busy添加到循环中以等待加载URL。我还在按钮点击循环中将input更改为button

Dim HTMLDoc As Object 'HTMLDocument
Dim oBrowser As Object 'InternetExplorer

Sub Website_Login()

Dim oHTML_Element As Object 'IHTMLElement
Dim sURL As String

sURL = "https://www.mypage.com/login.html"
Set oBrowser = CreateObject("InternetExplorer.Application") 'New InternetExplorer
'oBrowser.Silent = True
'oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True

With oBrowser
    Do While .Busy Or .ReadyState <> 4: Loop
End With


Set HTMLDoc = oBrowser.Document

With HTMLDoc
  HTMLDoc.getElementById("username").Value = "user"
  HTMLDoc.getElementById("password").Value = "password"
End With

For Each oHTML_Element In HTMLDoc.getElementsByTagName("button")
  If oHTML_Element.Name = "Submit" Then oHTML_Element.Click
  Exit For
Next

oBrowser.Quit

End Sub