我加载一个 Internet 页面并使用 VBA 使用 myusername
和 mypassword
登录。
我想使用 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/