在没有任何元素ID的情况下在VBA中操作网站

时间:2018-06-15 23:16:09

标签: html vba web-scraping

VBA相当新,所以希望答案正盯着我!

我正在尝试从网站上获取信息,该网站要求您登录,然后您才能访问数据

不幸的是,我似乎找不到通过登录页面的方法,主要是因为我在HTML代码中找不到任何元素或ID名称。我尝试通过标签名称拉,但我似乎无法让它工作

以下是没有我的登录输入的HTML代码示例,以及一个(仅使用“LOGIN”一词)

的示例

LogIn

当我输入登录信息时,它会生成“value =”mylogin“

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

没有看到网址。

您可以尝试以下方法。

Ⓐ如果它是页面上唯一/第一个输入框:

1)使用CSS选择器:

Set a = .document.querySelector("input[type='text']") '<==assuming is first input box on the page

2)使用tagName:

Set a = .document.getElementsByTagName("input")(0)

Ⓑ如果它位于页面上的第一个输入框

之后

您可以遍历DOM树或通过索引

引用相应的索引

1)使用CSS选择器:

Set a = .document.querySelectorAll("input[type='text']") '<==assuming is first input box on the page
a.item(1).innerText '<== 1 is an example index position
'a(1).innerText  ''< or potentially this syntax

2)使用tagName和索引位置

Set a = .document.getElementsByTagName("input")(1)

Ⓒ可选的其他CSS选择器:

只是为了提供一些有关selectors ...

的更多信息

您可以使用adjacent sibling CSS选择器(+)尝试选择器,并使用类.modal-Header定位div标记后的输入标记:

.document.querySelector("div.modal-Header  + input")

示例代码用法:

Option Explicit
Public Sub GetInfo()
    Dim IE As New InternetExplorer
    Const URL = "yourURL"
    Application.ScreenUpdating = True
    With IE
        .Visible = False
        .navigate URL

        While .Busy Or .readyState < 4: DoEvents: Wend

        Set a = .document.querySelector("input[type='text']") '<==assuming is first input box on the page
        'Set a = .document.getElementsByTagName("input")(0)
        a.Focus
        a.innerText = "yourLogin"
        'Other code
        '.Quit
    End With
    Application.ScreenUpdating = True
End Sub