我正在尝试使用 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 打开,但它没有输入用户/密码并单击按钮。
请问有什么帮助吗?
最佳答案
我刚刚测试了这段代码并且它有效。
唯一的区别是我使用了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
关于javascript - 在网页上的登录表单中输入用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33637622/