用于操作基于Excel数据的表单的IE脚本



我正在尝试:

  1. 打开一个特定的URL&传递登录信息
  2. 从Excel获取数据并搜索指定的数据
  3. 搜索完成后,将数据字段操作为关联Excel数据,并在应用程序中执行几个命令
  4. 关闭IE或循环搜索数据中的下一个单元格

我尝试过使用VBA窗体和模块。

我在网上发现了这个代码,它似乎曾经可以通过我的凭据,但我无法再次使用它。

这些对象CCD_ 1&all.password会作为ID在网页的源代码中找到吗?

HTMLDoc.all.Email.Value = "email@example.com"
HTMLDoc.all.Password.Value = "ex5566"

Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
Sub Login_2_Website() 
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = "example.com"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True
Do
' Wait till the Browser is loaded
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.Document
HTMLDoc.all.Email.Value = "email@example.com"
HTMLDoc.all.Password.Value = "ex5566"
For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next
' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub

我认为您可以使用与查找提交按钮相同的代码来查找电子邮件和密码元素。如果您知道这些元素的名称或id(通过检查页面的html代码),则可以使用例如If oHTML_Element.Name = "password" then oHTML_Element.Value = "ex5566"

如果特定元素有ID,您也可以使用oHTML_Element = document.getElementById("[id of element]") oHTML_Element.Value = "password"直接访问它们。如果它们没有ID,但只有名称,也可以这样做,但您必须查明名称是否被多次使用。

web开发人员可以随心所欲地命名他们的输入、按钮、表单、id。电子邮件可以命名为电子邮件、ID、用户名或XYZ,这就是为什么您必须检查网站中的元素,以便相应地构建代码。让我们以twitter为例。

<input class="js-username-field email-input js-initial-focus" type="text" name="session[username_or_email]" autocomplete="on" value="" placeholder="Phone, email or username">

该标签是一个input标签,类名为js-username-field email-input js-initial-focus,上面没有ID,因此您不能使用HTMLDoc.getElementByID,必须使用HTMLDoc.getElementsByClassName,也可以使用all.email0,但如果有多个输入,则必须循环它们并正确检测所需的输入。

这比听起来容易,但你必须有一些HTML的基本知识。继续推特,密码的标签是:

<input class="js-password-field" type="password" name="session[password]" placeholder="Password">

不同的类和不同的名称来区分两者。最后是登录/提交按钮:

<button type="submit" class="submit EdgeButton EdgeButton--primary EdgeButtom--medium">Log in</button>

有了这3部分HTML元素,您可以通过以下方式登录:

HTMLDoc.getElementsByClassName("js-username-field email-input js-initial-focus")(0).Value = "email@example.com"
HTMLDoc.getElementsByClassName("js-password-field")(0).Value = "ex5566"
HTMLDoc.getElementsByClassName("submit EdgeButton EdgeButton--primary EdgeButtom--medium")(0).Click

(0)是什么意思?在HTML中,可以有许多具有相同类名的标记,并且当您调用getElementsByClassName时,它们都在一个数组中,因为登录站点只有1个具有这些类名的标签,所以数组位置"0"就是您要查找的位置。

同样,开发人员可以命名类、id和他们想要的任何东西,因此您需要检查网站以正确地编写脚本。

最新更新