excel - 使用 Excel VBA 写入 HTML 输入字段

标签 excel vba web getelementsbytagname input-field

我加载一个 Internet 页面并使用 VBA 使用 myusernamemypassword 登录。

我想使用 VBA 在网页的输入字段中编写搜索词。

因为输入框里没有名字和ID,所以没有成功

这是我的代码:

Sub MyLogin()

Dim IE As InternetExplorer
Set IE = CreateObject("InternetExplorer.Application")
With IE
    .Visible = True
    .navigate "https://www.example.com"

    Do Until .readyState = 4
        DoEvents
    Loop

    .document.all.Item("username").Value = "myusername"
    .document.all.Item("password").Value = "mypassword"
    .document.forms(0).submit

End With

Do Until IE.readyState = 4
    DoEvents
Loop

Dim inputfield As HTMLInputElement
For Each inputfield In IE.document.getElementsByTagName("input")
    If inputfield.Type = "text" Then inputfield.Value = "mysearch"
Next

Do Until IE.readyState = 4
    DoEvents
Loop

End Sub

我要填写的 HTML 字段:

input class="input-inboxsearch form-control" type="text" value="" placeholder="Nom, email" maxlength="71"

如何设置输入框的值?

最佳答案

根据@Miqi180 的评论,您可以尝试将以 Dim inputfield As HTMLInputElement 开头的代码部分替换为:

Dim inputfield As Object
Set inputfield = IE.document.getElementsByClassName("input-inboxsearch form-control")
If inputfield.length > 0 Then
    inputfield(0).Value = "mysearch"
End If

'carry on with your code

getElementsByClassName 方法将返回一个集合,因此您必须检查其长度,然后访问集合中的项目。如果只有一个元素属于该类,那么您可以引用集合中的第 0 个元素。

我已将 inputfield 变量设置为 Object,因为您似乎在使用后期绑定(bind)。

关于excel - 使用 Excel VBA 写入 HTML 输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38804174/

相关文章:

excel - 使用 VBA 在 Excel 中将主电子表格拆分为多个工作表

R函数等于excel CHIINV

javascript - 如何避免网站使用本地缓存的JavaScript文件?

excel - 用分隔列展开表

php - 如何在没有内存耗尽的情况下导出具有数字格式的 100K 记录的 HTML 表格

VBA 将特定单元格复制到特定工作表

c# - 使用 Excel Interop 手动编译 PERSONAL.xlsb 时,将快捷键分配给 VBA 宏?

vba - 如何在VBA中指定当前目录作为路径?

html - 网页 : Multiple scroll areas with variable height

java - Spring 启动: Getting Null inputs from Form Submission