javascript - 在网页上的登录表单中输入用户名和密码

标签 javascript vba excel

我正在尝试使用 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/

相关文章:

vba - 为什么IsNumeric (“1.23D45”)返回True?

excel - 使用公共(public) VBA 函数更改 Excel 中的单元格颜色背景 - 不是 VBA 程序员

javascript - 移除渲染组件时的 Vue 内存泄漏

javascript - 用 Jquery 替换哈希链接 anchor 的行为

javascript - 通过 Javascript 错误将考试时间设置为 30 分钟?

excel - 在 VBA 中将变量从窗体传递到模块

excel - 保存文件时忽略斜线

sql-server - 如何使用 SSIS 通过 foreach 循环容器调整记录集中的变量类型

vba - 什么时候在 VBA 中使用 Workbooks.Close?

javascript - 如何将数字保存到 localStorage 中,每次用户输入新数字时该数字都会递增?