VBA在搜索框IE中插入数据



>当我在搜索框中插入几个单词时,它会获取相关数据。我需要从中选择第一个选项。

有一个网站"https://indiarailinfo.com/"当我从电台框中搜索"ADI"时,系统获取名称中包含"ADI"的相关电台?第一个选项始终显示与它非常接近的匹配。如何使用 vba 代码从中选择第一个选项

Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.navigate "https://indiarailinfo.com/"
While ie.readyState <> 4: DoEvents: Wend
ie.Visible = True
ie.document.querySelector("[placeholder='from station']").Value = "ADI"

可以从该站点获得 HTML 代码

它在下拉列表中带来第一个答案,例如"ADI/艾哈迈达巴德交界处"我怎样才能在选定的答案中得到这个答案"

敬请建议

自动化纯粹主义者不喜欢使用 javascript 来执行,但我将在这里使用 IE 来触发下拉列表。如果我走纯路线,我会使用硒。

Option Explicit   
Public Sub MakeSelection()
    Dim ie As InternetExplorer, t As Date, dropdown1 As Object
    Set ie = New InternetExplorer
    Const MAX_WAIT_SEC As Long = 5
    With ie
        .Visible = True
        .Navigate2 "https://indiarailinfo.com/"
        While .Busy Or .readyState < 4: DoEvents: Wend
        With .document.querySelector("[placeholder='from station']")
            .Focus
            .Value = "ADI"
            ie.document.parentWindow.execScript "document.querySelector('[placeholder^=from]').click();"
        End With
        t = Timer
        Do
            DoEvents
            On Error Resume Next
            Set dropdown1 = .document.querySelectorAll(".icol span")
            On Error GoTo 0
            If Timer - t > MAX_WAIT_SEC Then Exit Do
        Loop While dropdown1.Length = 0
        If dropdown1.Length > 0 Then
            dropdown1.item(0).Click
        End If
        Stop
        .Quit
    End With
End Sub

对于使用硒碱性的自动化纯粹主义者

Option Explicit    
Public Sub MakeSelection()
    Dim d As WebDriver
    Set d = New ChromeDriver
    Const Url = "https://indiarailinfo.com/"
    With d
        .Start "Chrome"
        .get Url
        .FindElementByCss("[placeholder='from station']").SendKeys "ADI"
        .FindElementByCss(".icol span").Click
        Stop
        .Quit
    End With
End Sub

最新更新